小编use*_*596的帖子

子文件夹中的Python随机行

我在多个子文件夹中的.txt文件中有很多任务.我试图从这些文件夹,它们包含的文件以及文件中的文本行中随机选取总共10个任务.应删除或标记选定的行,以便在下次执行时不会选择它.这可能是一个太宽泛的问题,但我很欣赏任何意见或方向.

这是我到目前为止的代码:

#!/usr/bin/python  
import random   
with open('C:\\Tasks\\file.txt') as f:  
    lines = random.sample(f.readlines(),10)    
print(lines)
Run Code Online (Sandbox Code Playgroud)

python random-sample python-3.x

6
推荐指数
2
解决办法
1814
查看次数

Python:Traceback codecs.charmap_decode(input,self.errors,decoding_table)[0]

以下是示例代码,目的只是合并来自give文件夹及其子文件夹的文本文件.我偶尔会得到Traceback所以不知道在哪里看.还需要一些帮助来增强代码以防止空行被合并并在合并/主文件中不显示任何行.在合并文件之前,可能需要进行一些清理或者在合并过程中忽略空行,这可能是个好主意.

文件夹中的文本文件不超过1000行,但聚合主文件可以非常容易地跨越10000多行.

import os
root = 'C:\\Dropbox\\ans7i\\'
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list]
out_file = open('C:\\Dropbox\\Python\\master.txt','w')
for path,f_name in files:
    in_file = open('%s/%s'%(path,f_name), 'r')

    # write out root/path/to/file (space) file_contents
    for line in in_file:
        out_file.write('%s/%s %s'%(path,f_name,line))
    in_file.close()

    # enter new line after each file
    out_file.write('\n')

with open('master.txt', 'r') as f:
  lines = f.readlines()
with open('master.txt', 'w') as f:
  f.write("".join(L for L in lines if L.strip())) 



Traceback (most recent call last):
  File "C:\Dropbox\Python\master.py", line 9, in …
Run Code Online (Sandbox Code Playgroud)

python file-io traceback python-3.x python-unicode

3
推荐指数
2
解决办法
2万
查看次数