Wednesday, December 25, 2024
Google search engine
HomeLanguagesFile flush() method in Python

File flush() method in Python

The flush() method in Python file handling clears the internal buffer of the file. In Python, files are automatically flushed while closing them. However, a programmer can flush a file before closing it by using the flush() method. 

Syntax of flush() method

Syntax: fileObject.flush()
Return: This method does not require any parameters and it does not return anything.

Example 1:

Now let us look at the below example which illustrates the use of the flush() method. Before going through the program a text file gfg.txt is created having the below content. 

File flush() method in Python

 

In the below program, the gfg.txt is opened in reading mode then the flush() method only clears the internal buffer of the file, it does not affect the content of the file. So, the contents of the file can be read and displayed.

Python3




# opening the file in read mode
fileObject = open("gfg.txt", "r")
 
# clearing the input buffer
fileObject.flush()
 
# reading the content of the file
fileContent = fileObject.read()
 
# displaying the content of the file
print(fileContent)
 
# closing the file
fileObject.close()


Output: 

Geeks 4 Lazyroar!

Example 2:

In this program initially, we create a gfg.txt file and write Geeks 4 Lazyroar! as content in it and then we close the file. After that, we read and display the contents of the file, and then the flush() method is called which clears the input buffer of the file so the file object reads nothing and file content remains an empty variable. Hence nothing is displayed after the flush() method.

Python3




# program to demonstrate the use of flush()
 
# creating a file
fileObject = open("gfg.txt", "w+")
 
# writing into the file
fileObject.write("Geeks 4 Lazyroar !")
 
# closing the file
fileObject.close()
 
 
# opening the file to read its content
fileObject = open("gfg.txt", "r")
 
# reading the contents before flush()
fileContent = fileObject.read()
 
# displaying the contents
print("\nBefore flush():\n", fileContent)
 
 
# clearing the input buffer
fileObject.flush()
 
# reading the contents after flush()
# reads nothing as the internal buffer is cleared
fileContent = fileObject.read()
 
# displaying the contents
print("\nAfter flush():\n", fileContent)
 
# closing the file
fileObject.close()


Output: 

Before flush():
Geeks 4 Lazyroar!

After flush():

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments