如何在 Python 中连接文本文件? [英] How do I concatenate text files in Python?

查看:25
本文介绍了如何在 Python 中连接文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of 20 file names, like ['file1.txt', 'file2.txt', ...]. I want to write a Python script to concatenate these files into a new file. I could open each file by f = open(...), read line by line by calling f.readline(), and write each line into that new file. It doesn't seem very "elegant" to me, especially the part where I have to read/write line by line.

有没有更优雅"的在 Python 中如何做到这一点?

Is there a more "elegant" way to do this in 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 无论如何都应该处理这些描述符.我只是觉得很有趣

Sadly, this last method leaves a few open file descriptors, which the GC should take care of anyway. I just thought it was interesting

这篇关于如何在 Python 中连接文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆