这应该做
对于大文件:
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还是应该照顾这些文件描述符。我只是觉得很有趣



