Flush File Contents Manually Using flush() in Python

In Python, the flush() method is used to manually flush the internal buffer of a file, ensuring that all data written to the file is immediately saved to the disk. This is useful when working with large files or real-time logging, where you need to ensure that data is written instantly without waiting for Python’s automatic buffer flushing.


Examples

1. Flushing File Contents After Writing Data

In this example, we write data to a file and manually flush it using the flush() method to ensure that the contents are immediately written to the disk.

main.py

</>
Copy
# Open a file in write mode
file = open("example.txt", "w")

# Writing data to the file
file.write("Hello, this is a test message.\n")

# Manually flushing the buffer
file.flush()

# Keeping the file open to demonstrate further operations
input("Press Enter to close the file...")

# Closing the file
file.close()

Explanation:

Here’s how this works:

  1. The open() function creates a file example.txt in write mode.
  2. The write() method writes a string to the file buffer.
  3. The flush() method forces the buffer to be written to the file immediately.
  4. The program waits for user input before closing the file to ensure that we can check the contents.

Output:

The contents are immediately saved to “example.txt” even before closing the file.

2. Flushing File Contents in a Loop

When writing data continuously in a loop, using flush() ensures that each update is written to the file in real-time.

main.py

</>
Copy
import time

# Open a file in write mode
file = open("log.txt", "w")

# Writing multiple lines with flush
for i in range(5):
    file.write(f"Log entry {i+1}\n")
    file.flush()  # Ensure each entry is saved immediately
    time.sleep(1)  # Simulate a delay

# Closing the file
file.close()

Explanation:

  1. The file log.txt is opened in write mode.
  2. A loop writes five log entries, one per second.
  3. The flush() method ensures that each entry is written to the file immediately.
  4. The time.sleep(1) function adds a delay to simulate real-time logging.

Output:

Log entry 1
Log entry 2
Log entry 3
Log entry 4
Log entry 5

3. Flushing File Contents for Real-Time Logging

When logging errors or system events, using flush() ensures that logs are recorded instantly, preventing data loss in case of a crash.

main.py

</>
Copy
import sys

# Open a log file
log_file = open("error_log.txt", "w")

# Redirect standard output to the log file
sys.stdout = log_file

print("Error: Connection lost. Retrying...")
sys.stdout.flush()  # Ensure message is written immediately

# Reset stdout back to default
sys.stdout = sys.__stdout__

# Closing the log file
log_file.close()

Explanation:

  1. The file error_log.txt is opened in write mode.
  2. The standard output (sys.stdout) is redirected to the file.
  3. The print() statement writes an error message to the log file.
  4. The flush() method ensures that the message is written immediately.
  5. The standard output is restored to default after logging.

Output:

Error: Connection lost. Retrying...

Conclusion

Python’s flush() method is used to ensuring data is written to files immediately. Here’s a quick summary of when to use it:

  1. Ensuring immediate writes – Data is not lost in case of unexpected crashes.
  2. Real-time logging – Critical log messages are instantly available.
  3. Writing inside loops – Ensures each entry is recorded in time-sensitive applications.

By using flush(), you can improve the reliability of file writing operations in Python.