【发布时间】:2014-05-15 13:19:54
【问题描述】:
我想知道如何最好地处理在 python 中写入一个大文件。
我的 python 代码循环多次运行外部程序(具有奇怪输入文件格式的古代 Fortran),读取其输出(单行文件)进行一些非常简单的处理并写入编译的输出文件。外部程序执行速度很快(不到 1 秒)。
import subprocess as sp
f_compiled_out = open("compiled.output", "w")
for i in range(len(large_integer)):
write_input_for_legacy_program = prepare_input()
sp.call(["legacy.program"])
with open("legacy.output", "r") as f:
input = f.readline()
output = process(input)
f_compiled_out.write(output)
close(f_compiled_out)
我可以想到三个选项来生成编译的输出文件。
我已经在做什么了。
在主循环的每个循环中使用
open("comiled.output", "a") as f: f.write(output)打开 f_compiled_out使用 awk 进行简单的处理,并将输出 cat 放到“compiled.output”结尾。
那么(1)保持一个大文件打开并写入它的末尾与(2)打开并为每个写入附加它与(3)使用awk进行处理和@的开销是多少? 987654323@ 建立“compiled.output”。
在任何阶段都不需要将整个输出保存在内存中。
附:如果有人能看到任何其他明显的事情会随着 N_loops 变大而减慢速度,那也太棒了!
【问题讨论】:
-
这看起来很有希望...这是否允许我将遗留程序的输入和输出保留在内存中而不写入磁盘?注意我真的不想改变 Fortran 程序。
标签: python performance io