Skip to main content
 首页 » 编程设计

python之什么时候更新文件

2025年02月15日11leader

我有一组代码在无限循环中运行,通过带有控制 C 的终端取消。在这段代码中,我使用代码 json.dumps(dictionary,outfile)

我注意到,在我使用控件 C 终止进程之前,这实际上并没有将数据放入文件中。为什么文件直到程序终止后才更新?

请您参考如下方法:

Anthony Rossi 基本上是对的,您需要使用 outfile.flush() 刷新数据。但为什么会这样呢?

json.dump 需要一个“支持 .write() 的类文件对象”,参见 here .在您的代码中的某处,您使用了 open 来获取您的 outfile。如果我们查看 open 的文档,我们可以阅读以下内容:

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

  • Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

  • “Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.

我猜你没有指定 buffering 参数而且你的数据小于 4/8 kb。因此,写入是缓冲的,而不是直接写入文件。

当您使用 Ctrl+C 终止程序时,outfile 将关闭并将数据刷新到您的文件中。

要解决此问题,只需按照 Anthony Rossi 的建议将 outfile.flush() 放在 json.dump() 之后即可。