频繁地对一个文件对象调用write()是不是不好?

2024-10-02 10:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在重构一个可怕的python脚本,它是生成lua绑定的polycode项目的一部分。你知道吗

我正在考虑将lua行写出来,因为它们是以块的形式生成的。你知道吗

但我的一般问题是,快速写入文件有什么坏处/注意事项?

举个例子:

persistent_file = open('/tmp/demo.txt')

for i in range(1000000):
    persistent_file.write(str(i)*80 + '\n')


for i in range(2000):
    persistent_file.write(str(i)*20 + '\n')


for i in range(1000000):
    persistent_file.write(str(i)*100 + '\n')


persistent_file.close()

这只是一种简单的方法,基本上是以最快的速度写入文件。 我真的不希望碰到任何真正的问题这样做,但我想知道,这是有利于缓存一个大写?你知道吗


Tags: 文件项目in脚本forrange形式persistent
1条回答
网友
1楼 · 发布于 2024-10-02 10:24:26

open函数的文档中:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -> file object

...

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 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.

换句话说,在大多数情况下,您在频繁调用write()时遇到的唯一开销是函数调用的开销。你知道吗

相关问题 更多 >

    热门问题