Python按给定顺序将多个文件合并为一个大文件
我有多达8个独立的Python进程,它们在一个共享文件夹里创建临时文件。然后,我想让一个控制进程把所有的临时文件按特定的顺序合并成一个大文件。请问在不依赖特定操作系统的情况下,有什么最快的方法可以做到这一点?
12 个回答
7
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())
不过,要提醒你的是,如果你想对大文件的内容进行排序,这种方法可能会遇到一些问题。比如,如果你的临时文件中的最后一行使用了不同的换行格式,就会导致排序结果出现奇怪的情况。在这种情况下,你需要在读取临时文件的行时,先去掉这些行的换行符,然后再把统一的换行符写入大文件中(这意味着你需要多写一行代码)。
8
我不知道有没有什么命令可以直接把一个文件追加到另一个文件里。不过在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())
如果把文件全部读到内存里不太可行,或者不合适的话,你就需要逐个文件循环读取,分段处理。如果你的临时文件里有以换行符结束的行,可以逐行读入内存,你可以这样做:
# 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)
另外,还有一种方法是选择一个缓冲区大小,逐块读取文件,这种方法总是有效的,比如:
# 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
输入/输出的教程里有很多有用的信息。
42
这里用的是简单的文件输入输出:
# 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())
这段代码在不同的操作系统上都能用,算是比较通用的做法。而且它也很简单,性能应该和其他方法差不多。