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
Asked
Active
Viewed 7,257 times
5

radicaled
- 2,369
- 5
- 30
- 44
-
1you can only write unbuffered in binary mode - https://docs.python.org/3/library/functions.html#open – Moe May 26 '16 at 13:21
2 Answers
10
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"))

qvpham
- 1,896
- 9
- 17
9
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

Vorsprung
- 32,923
- 5
- 39
- 63
-
2Preferably use `with open("test.txt", "a") as my_file:` which closes and flushes upon leaving that context. – jrc Jun 10 '21 at 16:20
-
1@jrc i guess for some use cases you might not want to close the file – Vorsprung Jun 10 '21 at 18:54