以下是示例代码,目的只是合并给定文件夹及其子文件夹中的文本文件。我偶尔会得到 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 <module> for line in in_file:
File "C:\PYTHON32\LIB\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 972: character maps to <undefined>