0
0
Pythonprogramming~5 mins

Flushing and buffering concepts in Python

Choose your learning style9 modes available
Introduction

Flushing and buffering help control when data is actually sent out or saved. This makes programs faster and more efficient.

When you want to make sure a message appears immediately on the screen.
When writing data to a file and you want to save it right away.
When sending data over a network and need it sent without delay.
When you want to improve performance by grouping many small writes together.
When debugging and you want to see output before the program ends.
Syntax
Python
print('Hello', flush=True)

file.write('data')
file.flush()

Using flush=True in print() forces immediate output.

Calling flush() on a file makes sure all buffered data is written out.

Examples
This prints immediately without waiting.
Python
print('Hello world', flush=True)
This writes 'Hello' to the file and saves it right away.
Python
with open('file.txt', 'w') as f:
    f.write('Hello')
    f.flush()
This flushes the standard output buffer manually.
Python
import sys
sys.stdout.flush()
Sample Program

This program prints 'Start' immediately, waits 2 seconds, then prints 'End'.

Python
import time

print('Start', flush=True)
time.sleep(2)
print('End', flush=True)
OutputSuccess
Important Notes

Buffers collect data to send or save in bigger chunks for speed.

Flushing forces the buffer to empty right away.

Without flushing, output might appear delayed or all at once at the end.

Summary

Buffering groups data to improve speed.

Flushing sends buffered data immediately.

Use flushing to control when output appears or is saved.