这样就行了
对于大型文件:filenames = ['file1.txt', 'file2.txt', ...]with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
对于小文件:filenames = ['file1.txt', 'file2.txt', ...]with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
…也是我想到的另一个有趣的:filenames = ['file1.txt', 'file2.txt', ...]with open('path/to/output/file', 'w') as outfile:
for line in itertools.chain.from_iterable(itertools.imap(open, filnames)):
outfile.write(line)
遗憾的是,最后一种方法留下了一些打开的文件描述符,无论如何,GC都应该处理这些文件描述符。我只是觉得很有趣