from itertools import chain
infiles = [open('{}_example.txt'.format(i+1), 'r') for i in xrange(100)]
with open('example.txt', 'w') as fout:
for lines in chain(*infiles):
fout.write(lines)
我使用了这个,但问题是下一个文件的第一行与上一个文件的最后一行连接。
我不会一次打开所有文件,而是一次打开一个。此外,您实际上并不需要遍历这些行(使 Python 规范化并去除换行符);只需将文件作为一个整体读取(您甚至可以将它们作为二进制文件读取/写入,以防止 Python 以任何方式处理它们)。
fileNames = ['{}_example.txt'.format(i+1) for i in xrange(100)]
with open('example.txt', 'w') as fout:
for fileName in fileNames:
with open(fileName, 'r') as fin:
fout.write(fin.read())
fout.write('\n') # if you want that
尝试添加换行符
for lines in chain(*infiles):
fout.write(lines)
if not lines.endswith('\n'):
fout.write('\n')
正如mtth所建议的,您可以逐个文件地执行此操作:
from itertools import chain
infiles = [open('{}_example.txt'.format(i+1), 'r') for i in xrange(100)]
with open('example.txt', 'w') as fout:
for infile in infiles:
fout.write(infile.read())
fout.write('\n')