Python:如何改进Python中的流式文本文件编写

2024-05-14 01:07:21 发布

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

我正在学习如何用streaming strings as files in python来写作。

通常我用一个表达式

myfile = open("test.txt", w)
for line in mydata:
...     myfile.write(line + '\n')
myfile.close()

Python在目录中创建一个文本文件,并每隔一段时间逐块保存值。

我有以下问题:

是否可以设置缓冲区?(例如:每20 MB保存一次数据) 是否可以逐行保存?

谢谢你的建议,它们总是有助于改进


Tags: intesttxtforclose表达式asline
1条回答
网友
1楼 · 发布于 2024-05-14 01:07:21

python中的文件I/O已经被缓冲。使用^{} function可以确定缓冲的扩展写入:

The optional buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.

就我个人而言,我会通过with语句将该文件用作上下文管理器。当with套件下的所有语句(至少一个缩进级别更深)完成时,将引发异常,文件对象将关闭:

with open("test.txt", 'w', buffering=20*(1024**2)) as myfile:
    for line in mydata:
        myfile.write(line + '\n')

在上面的例子中,我将缓冲区设置为20MB。

相关问题 更多 >