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
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"))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With