我有 20 个文件名的列表,例如['file1.txt', 'file2.txt', ...]. 我想编写一个 Python 脚本来将这些文件连接成一个新文件。我可以通过调用打开每个文件f = open(...),通过调用逐行读取f.readline(),然后将每一行写入该新文件。对我来说,这似乎不是很“优雅”,尤其是我必须逐行读/写的部分。
['file1.txt', 'file2.txt', ...]
f = open(...)
f.readline()
在 Python 中是否有更“优雅”的方式来做到这一点?
这应该这样做
对于大文件:
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 无论如何都应该处理这些描述符。我只是觉得这很有趣