在Python3上无缓冲写入

2024-04-20 14:34:33 发布

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

我试图在python上创建一个没有缓冲区的文件,因此它是在我使用write()的同时编写的。但由于某种原因,我遇到了一个错误。
这是我使用的线路:

my_file = open("test.txt", "a", buffering=0) my_file.write("Testing unbuffered writing\n")

这是我得到的错误:
my_file = open("test.txt", "a", buffering=0) ValueError: can't have unbuffered text I/O

有什么办法对一个文件进行无缓冲写入? 我在pyCharm上使用python3。
谢谢


Tags: 文件testtxtmy错误opentesting线路
2条回答

错误不是来自Pycharm。在

来自Python文档:

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode)

您的代码只能在python2中工作,而不能在python3中工作。因为在python3中,字符串是Unicode代码点的不可变序列。你需要这里有字节。要在python3中实现这一点,您可以在无缓冲模式下将unicode str转换为bytes。在

例如:

my_file.write("Testing unbuffered writing\n".encode("utf-8"))

使用

my_file = open("test.txt", "a")
my_file.write("Testing unbuffered writing\n")
my_file.flush()

总是在写入后立即调用flush,它将“好像”它是无缓冲的

相关问题 更多 >