3

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?

4
  • 2
    but flush takes no arguments... they're not the same at all. The doc you copied shows an argument for write and none for flush. flush forces data written using write to be dumped to the media. Commented Feb 18, 2017 at 22:17
  • Have you tried using both functions? It should become clear that they do different things. Commented Feb 18, 2017 at 22:19
  • write() sends the data from your program into the IO subsystem where it may be buffered. flush() tells the IO subsystem that you would like to commit any data that has been buffered. Commented Feb 18, 2017 at 22:21
  • 1
    If you've not previously called write, flush will do nothing. Commented Feb 18, 2017 at 22:32

1 Answer 1

2

[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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.