【问题标题】:Python: when writing to a large file, keep the file open or to open it and append to it as needed?Python:写入大文件时,保持文件打开还是打开它并根据需要附加到它?
【发布时间】: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)

我可以想到三个选项来生成编译的输出文件。

  1. 我已经在做什么了。

  2. 在主循环的每个循环中使用 open("comiled.output", "a") as f: f.write(output) 打开 f_compiled_out

  3. 使用 awk 进行简单的处理,并将输出 cat 放到“compiled.output”结尾。

那么(1)保持一个大文件打开并写入它的末尾与(2)打开并为每个写入附加它与(3)使用awk进行处理和@的开销是多少? 987654323@ 建立“compiled.output”。

在任何阶段都不需要将整个输出保存在内存中。

附:如果有人能看到任何其他明显的事情会随着 N_loops 变大而减慢速度,那也太棒了!

【问题讨论】:

  • 这看起来很有希望...这是否允许我将遗留程序的输入和输出保留在内存中而不写入磁盘?注意我真的不想改变 Fortran 程序。

标签: python performance io


【解决方案1】:

打开和关闭文件肯定是有代价的。但是,如果您的旧程序需要一秒或更多秒来响应,您可能不会注意到。

def func1():
    for x in range(1000):
        x = str(x)
        with open("test1.txt", "a") as k:
            k.write(x)

1 loops, best of 3: 2.47 s per loop

def func2():
    with open("test2.txt", "a") as k:
        for x in range(1000):
            x = str(x)
            k.write(x)

100 loops, best of 3: 6.66 ms per loop

但是,如果您的文件变得非常大,它会变得更慢:(800+mb)

def func3(file):
    for x in range(10):
        x = str(x)
        with open(file, "a") as k:
            k.write(x)

12kb 文件:

10 loops, best of 3: 33.4 ms per loop

800mb+ 文件:

1 loops, best of 3: 24.5 s per loop

保持文件打开主要会消耗你的内存。

我建议使用 SQlite 来存储您的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-05
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2014-04-04
    相关资源
    最近更新 更多