ZetCode

Python flush function

last modified November 29, 2026 Python 3.15

In this article we show how to use the flush method to push buffered data out of a file object. We look at when another handle can see the data, line buffering, the difference between flush and fsync, and flushing standard output.

Buffering is set when the file is opened, as described in Python open function. Writing itself is covered in Python write function, and closing, which also flushes, in Python close function.

The write buffer

By default a file object collects writes in a buffer and passes them to the operating system in larger blocks. flush sends the buffer on demand.

flush_buffer.py
with open('notes.txt', 'w', encoding='utf-8') as f:
    print(f.write('milk\n'))
    with open('notes.txt', encoding='utf-8') as g:
        print(repr(g.read()))
    print(f.flush())
    with open('notes.txt', encoding='utf-8') as g:
        print(repr(g.read()))

write returns 5, but a second handle sees an empty file. flush returns None, and the same read then returns milk\n. The file is still open afterwards, so more writes can follow.

$ python flush_buffer.py
5
''
None
'milk\n'

Flush does not close

flush only empties the buffer. The file remains open and writable, unlike after close.

flush_open.py
with open('notes.txt', 'w', encoding='utf-8') as f:
    f.write('milk\n')
    f.flush()
    print(f.closed)
    f.write('bread\n')
    print(f.closed)

with open('notes.txt', encoding='utf-8') as g:
    print(repr(g.read()))

closed is False both before and after the flush. The file is closed at the end of the with block, and both lines are then visible. Python close function covers the closing step.

$ python flush_open.py
False
False
'milk\nbread\n'

Line buffering

buffering=1 selects line buffering in text mode: every newline flushes the buffer.

flush_line.py
with open('notes.txt', 'w', encoding='utf-8', buffering=1) as f:
    print(f.line_buffering)
    f.write('Paris\n')
    with open('notes.txt', encoding='utf-8') as g:
        print(repr(g.read()))
    f.write('Prague')
    with open('notes.txt', encoding='utf-8') as g:
        print(repr(g.read()))
    f.flush()
    with open('notes.txt', encoding='utf-8') as g:
        print(repr(g.read()))

line_buffering is True. The line with its newline is visible immediately, the write without a newline is not, and the explicit flush makes it visible. Standard output uses the same idea when it is attached to a terminal.

$ python flush_line.py
True
'Paris\n'
'Paris\n'
'Paris\nPrague'

Flushing in stages

A program that writes a log, and another reader that follows it, can flush after each record so that every record appears as soon as it is written.

flush_stages.py
with open('log.txt', 'w', encoding='utf-8') as f:
    for city in ['Paris', 'Prague', 'Vienna']:
        f.write(city + '\n')
        f.flush()
        with open('log.txt', encoding='utf-8') as g:
            content = g.read()
        print(content.count('\n'), repr(content))

After each flush the reader sees one more line, and the count grows from 1 to 3. Without the flush the reader could stay at 0 until the buffer fills or the file is closed.

$ python flush_stages.py
1 'Paris\n'
2 'Paris\nPrague\n'
3 'Paris\nPrague\nVienna\n'

Flush and fsync

flush moves data from Python's buffer to the operating system. os.fsync asks the operating system to write it to the storage device, which is a stronger guarantee and a slower call.

flush_fsync.py
import os

with open('notes.txt', 'w', encoding='utf-8') as f:
    f.write('Vienna\n')
    f.flush()
    os.fsync(f.fileno())

print('synced')

After the flush and the fsync the program prints synced, and the data has passed both layers. fsync needs the file descriptor that fileno returns. Use it for data that must survive a power loss, not for every line.

$ python flush_fsync.py
synced

Standard output

sys.stdout is a text file object with a buffer of its own. When it is connected to a terminal it is line buffered; when it is redirected to a file or a pipe it is block buffered.

flush_stdout.py
import sys

for step in ('read', 'parse', 'write'):
    print(f'step: {step}', flush=True)

sys.stdout.flush()
print('done')

Each step is printed with flush=True, so it appears before the next one is computed, even when the output is redirected. The final sys.stdout.flush() is redundant here but harmless. Running Python with -u makes the standard streams unbuffered, which is useful for logs from a long-running program.

$ python flush_stdout.py
step: read
step: parse
step: write
done

Two handles on one file

Two handles have separate buffers. Flushing each one after writing makes the data visible to the other.

flush_handles.py
with open('log.txt', 'w+', encoding='utf-8') as a, open('log.txt', 'a', encoding='utf-8') as b:
    a.write('first\n')
    a.flush()
    b.write('second\n')
    b.flush()
    a.seek(0)
    print(repr(a.read()))

The first handle writes and flushes, the second appends and flushes, and the first handle then reads both lines. Without the flushes the second write could be invisible to the read, because it would still sit in the second handle's buffer.

$ python flush_handles.py
'first\nsecond\n'

Source

IOBase.flush – Python documentation

os.fsync – Python documentation

sys.stdout – Python documentation

In this article we have flushed a buffer on demand, kept a file open after flushing, used line buffering, pushed data to the disk with fsync, and flushed standard output. See also Python open function, Python close function, and Python write function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.