9

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

1

2 Answers 2

12

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"))
Sign up to request clarification or add additional context in comments.

Comments

12

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

2 Comments

Preferably use with open("test.txt", "a") as my_file: which closes and flushes upon leaving that context.
@jrc i guess for some use cases you might not want to close the file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.