我有许多文本文件分散在许多子目录中。只想编译单个聚合文本文件。我的要求是生成应该具有目录结构的文本文件,包括文件名作为每行的前缀。TIA
问问题
420 次
1 回答
2
import os
root = './'
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list]
out_file = open('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')
out_file.close()
如果你只想要树中的一些文件,root
将第三行更改为
# only take .txt files from the directory tree
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list if f.endswith('.txt')]
于 2012-08-28T10:14:06.507 回答