我编写了一个Python程序,循环遍历X文件列表,打开每个文件,逐行读取,并将(追加)写入输出文件。由于这些文件每个都是几个GB,这需要花费很长时间。
我正在寻找建议,以提高这一方案的性能。我没有正式的CS培训,所以很可能我错过了这个问题的“明显的解决方案”;我已经做了一些研究,但我的有限知识(以及其他更高优先级的任务)限制了我实现这个问题的能力。
for name in PR_files:
with open(PR_path + name, 'r') as f:
line = f.readline()
while line:
with open(PR_out_path, 'a') as g:
g.write(line + '\n')
line = f.readline()
f.close()该程序将工作,但输出文本文件中的每一行之间将有一个空行;这是因为下一个文件的第一行开始于前一个文件的最后一行(我对这个问题的解决方案是将'\n'添加到写入输出文件的每一行中。因此,我编写了另一个块来删除输出文件中的所有空行(是的,我知道,效率很低)。
# this removes all blank lines from out put file
with open(PR_out_path) as this, open(PR_out_path_fix, 'w') as that:
for line in this:
if not line.strip():
continue
that.write(line)请注意:我尝试这样做,与逐行阅读相反,但我收到了一个MemoryError。
with open(PR_out_path, 'a') as g:
for name in PR_files:
with open(PR_path + name, 'r') as f:
g.write(f.read())发布于 2018-08-25 03:12:08
你的原始代码:
with open(PR_out_path, 'a') as g:
for name in PR_files:
with open(PR_path + name, 'r') as f:
g.write(f.read())工作,但正如您所发现的,如果无法将整个文件读入内存,则会出现问题。该问题的解决方案是以块形式读取输入文件:
with open(PR_out_path, 'a') as g:
for name in PR_files:
with open(PR_path + name, 'r') as f:
while True:
data = f.read(ChunkSize)
if not data:
break
g.write(data)其中ChunkSize大约是1GB。
但是,如果速度是你唯一的要求,为什么不使用操作系统提供的工具,正如其他人所指出的那样?
https://codereview.stackexchange.com/questions/202423
复制相似问题