Python连接文本文件

发布于 2021-02-02 23:20:00

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

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

关注者
0
被浏览
112
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    这应该做

    对于大文件:

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看