When working with files in Python, data is often not written directly to disk immediately. Instead, it is temporarily stored in a buffer. This improves performance, especially for large I/O operations. Understanding buffering and how to flush data manually is crucial for reliability in file handling.
flush()
is calledbuffering=0
for unbuffered, 1
for line-buffered, or specify an integer buffer size.with open('log.txt', 'w') as f:
f.write('Log started\\n')
# Automatically buffered, flushes on close
with open('log.txt', 'w') as f:
f.write('Important data\\n')
f.flush() # forces immediate write
# Binary mode required for buffering=0
with open('data.bin', 'wb', buffering=0) as f:
f.write(b'hello')
with open('data.txt', 'w', buffering=1) as f:
f.write("line1\\n") # Flushes on newline
with open('buffered.txt', 'w', buffering=8192) as f:
f.write('Buffered write with 8KB buffer')
import time
with open('progress.log', 'w') as f:
for i in range(5):
f.write(f"Step {i}\\n")
f.flush() # ensures each step is written immediately
time.sleep(1)
import sys
import time
for i in range(3):
print(f"Progress {i}", end=' ', flush=True)
time.sleep(1)
with open('temp.txt', 'w') as f:
f.write('Not flushed yet')
f.flush() # ensures data is on disk now
f = open('output.txt', 'w')
try:
f.write('Critical log entry\\n')
f.flush()
finally:
f.close()
import time
start = time.time()
with open('big.txt', 'w', buffering=1024) as f:
for _ in range(10000):
f.write('x' * 100 + '\\n')
print("Buffered:", time.time() - start, "sec")