How to flush the internal buffer in Python?


The purpose of internal buffers, which are created by the runtime, library, and programming language that you're using, is to speed up operations by preventing system calls on every write. Instead, when writing to a file object, you write into its buffer, and when the buffer is full, system functions are used to write the data to the actual file.

Syntax

Following is the syntax of flush() function −

File_name.flush()

No parameters are accepted by it.

This method returns nothing; its return type is <class 'nonetype'="">.

Example -1

The flush() method in the program below simply clears the file's internal buffer; the file's actual content is unaffected. As a result, the contents in the file can be read and seen −

# Create a file file = open("flush.txt", "w") # Write the text in the file file.write("Tutorials Point") # Flush the internal buffer file.flush() # Close the file file.close() # Read and write the content present in the file file = open("flush.txt", "r+") print("The content in the file is file.flush()") print(file.read()) file.close()

Output

Following is an output of the above code 

The content in the file is file.flush()
Tutorials Point

Example - 2

In the program below we created a text file writing some content in it and then closed the file. Following the reading and displaying of the file's contents, the flush() function is performed, clearing the file's input buffer so that the file object reads nothing and the file content variable remains empty. As a result, nothing is shown after the flush() procedure −

# Create a file file = open("flush.txt", "w+") # Write in the file file.write("Tutorials Point file.flush() is performed. The content isn't flushed") # Close the file file.close() # Open the file to read the content present in it file = open("flush.txt", "r") # Read the content present in the before flush() is performed Content = file.read() # dDisplay the contents print("\nBefore performing flush():\n", Content) # Clear the input buffer file.flush() # Read the content after flush() function is performed but reads nothing since the internal buffer is already cleared Content = file.read() # Display the contents now print("\nAfter performing the flush():\n", Content) # Close the file file.close()

Output

Following is an output of the above code −

Before performing flush():
Tutorials Point file.flush() is performed. The content isn't flushed
After performing the flush():

Updated on: 18-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements