在Python中使用缓冲区写入文件

时间:2019-09-24 11:44:27

标签: python python-3.x

我正在使用Tshark(命令行wireshark)来嗅探网络数据包,并将它们写到文件中,就像收到它们一样。我的代码块类似于以下内容:

documents = PriorityQueue(maxsize=0)
writing_enabled = True
with open("output.txt", 'w') as opened_file:
    while writing_enabled:
        try:
            data = documents.get(timeout=1)
        except Exception as e:
            #No document pushed by producer thread
            continue
        opened_file.write(json.dumps(data) + "\n")

如果我从Tshark线程接收文件,则将它们放入队列,然后另一个线程使用上面的代码将其写入文件。但是,文件达到600+ MB之后,进程会变慢,然后将状态更改为“无响应”。经过研究,我认为这是由于打开文件方法的默认缓冲机制所致。更改with open("output.txt", 'w') as opened_file:是否合理? 进入with open("output.txt", 'w', 1000) as opened_file:以在写入模式下使用1000字节的缓冲区?还是有另一种方法可以克服这个问题?

1 个答案:

答案 0 :(得分:2)

要将内部缓冲区写入文件,可以使用文件刷新功能。但是,这通常应由具有默认缓冲区大小的操作系统处理。如果您想指定自己的缓冲区大小,可以使用以下方法打开文件:

f = open('file.txt', 'w', buffering=bufsize)

也请参见以下问题:How often does Python flush to file

除了刷新缓冲区外,您还可以尝试使用滚动文件,即,如果当前打开的文件的大小超过特定大小,则打开一个新文件。如果您打算写入大量数据,通常这是个好习惯。