Writes to a file go into a buffer in memory first, which is much faster than touching the disk for every call. flush() hands everything in that buffer to the operating system right now, and the file stays open.
After a flush, another program or another open() of the same file can read the data. For a guarantee that it is physically on the disk, follow it with os.fsync(f.fileno()).
file.flush() is a method of the file objects that the built-in open() returns, so no import is needed. It works on text files (TextIOWrapper), binary files (BufferedReader, BufferedWriter, BufferedRandom), and raw files (FileIO, opened with buffering=0).
Syntax
Call it with no arguments on a file opened for writing.
python
f.write(text)
f.flush()
Call
What it does
f.flush()
Sends pending writes to the OS; returns None.
f.close()
Also flushes, then closes. A with block does this for you.
os.fsync(f.fileno())
After flush(): asks the OS to write its own cache to disk.
print(..., flush=True) and open(..., buffering=1) (line buffering, text only) are shortcuts that flush for you.
Method signatures
python
TextIOWrapper.flush() # -> None, also flushes the binary buffer below
BufferedWriter.flush() # -> None
FileIO.flush() # -> None, nothing is buffered at this level
Parameters
flush() takes no parameters.
Return Value
Return Value
Description
None
Always. Errors from the operating system, such as a full disk, are raised as OSError.
Python Examples
Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.
Example 1 — Make a Checkpoint Visible to a Second Reader
Write with print(file=...), flush, and read the same file through another handle while the writer is still open.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "progress.txt")
with open(path, "w", encoding="utf-8") as writer:
print("checkpoint", 1, file=writer)
result = writer.flush()
with open(path, encoding="utf-8") as reader:
print(repr(reader.read()), result)
Output
'checkpoint 1\n' None
How It Works
Buffered write.print(..., file=writer) puts checkpoint 1\n into the text buffer, not yet into the file.
Push it down.writer.flush() sends the bytes to the operating system and returns None.
Second handle sees it. The reader opens the same path while the writer is still open and gets the full line.
Example 2 — Watch a File Grow After Each flush()
Write two blocks of a pretend upload and check the size on disk after every flush.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "upload.part")
with open(path, "wb") as f:
for block in (b"x" * 100, b"y" * 50):
f.write(block)
f.flush()
print("on disk:", os.path.getsize(path))
print("after close:", os.path.getsize(path))
Output
on disk: 100
on disk: 150
after close: 150
How It Works
Binary blocks.b"x" * 100 builds 100 bytes; the second block adds 50.
Size follows flush. After each flush(), os.path.getsize() sees every byte written so far.
Close adds nothing new. The final size is still 150, because the last flush already emptied the buffer.
Example 3 — Keep a Durable Journal with flush() and os.fsync()
Append three steps, making each one visible and durable before the next, then flush a closed file.
python
import os
import tempfile
def count_lines(path):
with open(path, encoding="utf-8") as f:
return len(f.readlines())
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "journal.txt")
f = open(path, "w", encoding="utf-8")
for step in range(1, 4):
f.write(f"step {step} done\n")
f.flush()
os.fsync(f.fileno())
print("lines visible:", count_lines(path))
f.close()
try:
f.flush()
except ValueError:
print("flush() after close() raises ValueError")
Two-step durability.flush() moves data from Python to the OS; os.fsync(f.fileno()) asks the OS to commit it to the storage device.
Independent check.count_lines() opens its own handle, so each count proves the step really left the writer's buffer.
Manual close. Without a with block, f.close() must be called explicitly before the folder is removed.
Closed means closed. Flushing after close() raises ValueError, which the except turns into a fixed message.
Frequently Asked Questions
It moves data from the file object's memory buffer to the operating system, so other readers can see it. The file stays open.
No. close() flushes automatically, and leaving a with block calls close(). Call flush() only when the file must stay open and others need the data now.
Not quite. flush() hands data to the OS, which may still cache it. Call os.fsync(f.fileno()) after flush() for durable storage.
Small writes sit in the buffer until it fills. Call flush() after important writes, use print(..., flush=True), or open the file with buffering=1 for line buffering.
It is allowed and simply does nothing useful. On a closed file it raises ValueError.