小编典典

Python连接文本文件

python

我列出了20个文件名,例如['file1.txt', 'file2.txt', ...]。我想编写一个Python脚本将这些文件连接成一个新文件。我可以通过打开每个文件f = open(...),通过调用逐行读取f.readline(),然后将每一行写入该新文件。在我看来,这并不是很“优雅”,尤其是我必须逐行读取/写入的部分。

在Python中是否有更“优雅”的方式来做到这一点?


阅读 451

收藏
2020-02-14

共1个答案

小编典典

这应该做

对于大文件:

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

2020-02-14