Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write unbuffered on python 3

Tags:

python

pycharm

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

like image 868
radicaled Avatar asked May 09 '26 22:05

radicaled


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"))
like image 83
qvpham Avatar answered May 11 '26 11:05

qvpham


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

like image 24
Vorsprung Avatar answered May 11 '26 12:05

Vorsprung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!