Python File flush() Method



The Python File flush() method flushes the internal buffer. This internal buffer is maintained to speed up file operations.

For instance, whenever a write operation is performed on a file, the contents are first written in the internal buffer; which is then transferred into the destination file once the buffer is full. This is done to prevent frequent system calls for every write operation. And once the file is closed, Python automatically flushes the buffer. But you may still want to flush the data before closing any file.

The method works similar to the stdio's fflush and may be a no-op on some file-like objects.

Syntax

Following is the syntax for the Python File flush() method −

fileObject.flush(); 

Parameters

The method does not accept any parameters.

Return Value

This method does not return any value.

Example

The following example shows a simple program using the Python File flush() method.

# Open a file
fo = open("foo.txt", "wb")
print("Name of the file: ", fo.name)

# Here it does nothing, but you can call it with read operation.
fo.flush()

# Close opened file
fo.close()

When we run above program, it produces following result −

Name of the file:  foo.txt

Example

When we use the flush() method, it does not flush the original file but just the internal buffer contents.

In the example below, we open a file in the read mode and the file contents are read. Then, the internal buffer is flushed using the flush() method. The contents in the file are printed to check whether the method modified the original file or not.

# Open a file
fo = open("hello.txt", "r")
print("Name of the file: ", fo.name)

file_contents = fo.read()

fo.flush()

print("Contents of the file: ", file_contents)

# Close opened file
fo.close()

On executing the program above, the result is obtained as follows −

Name of the file:  hello.txt
Contents of the file:  hello

Example

Even if the method is not called, Python flushes the internal buffer contents once the file is closed.

# Open a file
fo = open("test.txt", "w")

#Perform an operation on the file
print("Name of the file: ", fo.name)

# Close opened file
fo.close()

If we compile and run the program above, the output is displayed as follows −

Name of the file:  test.txt
python_file_methods.htm
Advertisements