gpt4 book ai didi

python - 在 python 3 上无缓冲地写入

转载 作者:行者123 更新时间:2023-12-04 14:34:44 25 4
gpt4 key购买 nike

我试图在没有缓冲区的情况下在 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 上使用 python 3。
谢谢

最佳答案

错误不是来自 Pycharm。

来自 Python 文档:

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



您的代码仅适用于 Python 2 但不适用于 Python 3 .因为 字符串 中 Unicode 代码点的不可变序列Python 3 .你需要在这里有字节。在 中做Python 3 您可以转换您的 unicode strbytes在无缓冲模式下。

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

关于python - 在 python 3 上无缓冲地写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37462011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com