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

标签 python pycharm

我试图在没有缓冲区的情况下在 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/

相关文章:

python - PyCharm 未检测到 anaconda3 环境

python - 我可以将图像列表传递给ffmpeg-python的输入法吗

python - 如何在pycharm中中断 `pass`

python - Pycharm 调试器比正常运行慢得多

python 3 : How do I get a string literal representation of a byte string?

PyCharm arcpy 导入时出现 Python 套接字服务器错误 - 我没有设置什么?

python - 如何自动完成所有参数列表以在 PyCharm 中运行?

python - 如何在 tkinter 中用箭头连接两个状态圆圈?

python - 在子图之间画一条线

python - 如何禁用 pytest.ini 中的多个插件?