Python将给定顺序的多个文件附加到一个大文件中

Mar*_*ark 15 python file append

我有多达8个单独的Python进程在共享文件夹中创建临时文件.然后我想控制进程将所有临时文件按特定顺序附加到一个大文件中.在os不可知的shell级别上执行此操作的最快方法是什么?

Raf*_*ler 27

只使用简单的文件IO:

# tempfiles is a list of file handles to your temp files. Order them however you like
f = open("bigfile.txt", "w")
for tempfile in tempfiles:
    f.write(tempfile.read())
Run Code Online (Sandbox Code Playgroud)

这就像操作系统不可知一样.它也相当简单,性能应该与使用其他任何东西一样好.

  • 这仅在每个单独的文件足够小以便读入内存时才有效.如果您可以并行读取和写入(例如,不同的磁盘或架构允许这样做),那么性能也会更差,因为您将在开始任何操作之前等待读取文件.使用shutil.copyfileobj可能会更好 (12认同)

Cpt*_*Luc 8

不知道任何用于将一个文件附加到另一个文件的shell级命令.但附加在'python级别'是非常容易的,我猜python开发人员认为没有必要将它添加到库中.

解决方案取决于要附加的临时文件的大小和结构.如果它们都足够小,你不介意将它们全部读入内存,那么Rafe Kettler的答案(从他的答案复制并在下面重复)以最少的代码完成工作.

# tempfiles is an ordered list of temp files (open for reading)
f = open("bigfile.txt", "w")
for tempfile in tempfiles:
    f.write(tempfile.read())
Run Code Online (Sandbox Code Playgroud)

如果无法将文件完全读入内存或不是一个合适的解决方案,您将需要遍历每个文件并逐个读取它们.如果你的临时文件包含可以单独读入内存的换行终止行,你可能会这样做

# tempfiles is an ordered list of temp files (open for reading)
f = open("bigfile.txt", "w")
for tempfile in tempfiles:
    for line in tempfile
        f.write(line)
Run Code Online (Sandbox Code Playgroud)

或者 - 一直有效的东西 - 你可以选择一个缓冲区大小,然后只是逐个读取文件,例如

# tempfiles is an ordered list of temp files (open for reading)
f = open("bigfile.txt", "w")
for tempfile in tempfiles:
    while True:
        data = tempfile.read(65536)
        if data:
            f.write(data)
        else:
            break
Run Code Online (Sandbox Code Playgroud)

输入/输出教程有很多好的信息.


kse*_*sed 6

Rafe的答案是缺乏适当的开/闭陈述,例如

# tempfiles is a list of file handles to your temp files. Order them however you like
with open("bigfile.txt", "w") as fo:
     for tempfile in tempfiles:
          with open(tempfile,'r') as fi: fo.write(fi.read())
Run Code Online (Sandbox Code Playgroud)

但是,要预先警告,如果要对bigfile的内容进行排序,此方法不会捕获一个或多个临时文件中的最后一行具有不同EOL格式的实例,这会导致一些奇怪的排序结果.在这种情况下,您需要在读取时删除临时文件行,然后将一致的EOL行写入bigfile(即涉及额外的代码行).