I'm trying to create a file on python without buffer, so its written at the same time I use write(). But for some reason I got an error.
This is the line I'm using:
my_file = open("test.txt", "a", buffering=0)
my_file.write("Testing unbuffered writing\n")
And this is the error I got:
my_file = open("test.txt", "a", buffering=0)
ValueError: can't have unbuffered text I/O
There is anyway to do an unbuffered write on a file?
I'm using python 3 on pyCharm.
Thanks
-
2you can only write unbuffered in binary mode - docs.python.org/3/library/functions.html#openMoe– Moe2016-05-26 13:21:31 +00:00Commented May 26, 2016 at 13:21
Add a comment
|
2 Answers
The error isn't from Pycharm.
From Python documentation:
buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode)
Your code only works in Python 2 but won't work in Python 3. Because Strings are immutable sequences of Unicode code points in Python 3. You need to have bytes here. To do it in Python 3 you can convert your unicode str to bytes in unbuffered mode.
For example:
my_file.write("Testing unbuffered writing\n".encode("utf-8"))
Comments
use
my_file = open("test.txt", "a")
my_file.write("Testing unbuffered writing\n")
my_file.flush()
Always call flush immediately after the write and it will be "as if" it is unbuffered