user2762934
user2762934

Reputation: 2452

Python: file.write() versus file.flush()

What really is the difference between file.write() and file.flush()?

From Python's official documentation, I get this:

flush() Force bytes held in the buffer into the raw stream. A BlockingIOError should be raised if the raw stream blocks.

write(b) Write the bytes-like object, b, and return the number of bytes written. When in non-blocking mode, a BlockingIOError is raised if the buffer needs to be written out but the raw stream blocks.

To the best of my newbie understanding, they both transfer information currently held in memory to a file on disk. The difference however that write() also returns information on how much information was stored, while flush() performs this task immediately. Is that correct? In what circumstances would it then be preferable to apply write() over flush() and vice-versa?

Upvotes: 3

Views: 8771

Answers (1)

Jarak
Jarak

Reputation: 982

[See also the comments by Stephen Rauch and Peter Wood] Think about it in the context of a stream that is connected to something that is reading from that stream at the other end.

write(b) contributes b to that stream's buffer on your end. It may or may not actually put all those bytes in so that they are 'sent' down the stream to the reader at the other end.

flush() on the other hand takes everything that is in the stream's buffer, and 'sends' it to the reader.

Basically, you use write(b) to load your data onto the stream, and then you all flush() at the end to make sure that everything has actually gone into the underlying stream and 'been sent', rather than sitting in the stream's buffer.

So, for example, if I connect my computer to another device using the PySerial package (which creates a serial connection that effectively works as a stream), then to put some data into that stream, I will use write(b). To make certain that all that data has gone through the serial connection and through to the other device however, I will call flush(). This is because write(b) doesn't guarantee that all (or any in fact) of that data will actually be sent to the other device immediately.

Upvotes: 2

Related Questions