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.
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
fileObject = open ( "gfg.txt" , "r" )
fileObject.flush()
fileContent = fileObject.read()
print (fileContent)
fileObject.close()
|
Output:
Geeks 4 geeks!
Example 2:
In this program initially, we create a gfg.txt file and write Geeks 4 geeks! 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
fileObject = open ( "gfg.txt" , "w+" )
fileObject.write( "Geeks 4 geeks !" )
fileObject.close()
fileObject = open ( "gfg.txt" , "r" )
fileContent = fileObject.read()
print ( "\nBefore flush():\n" , fileContent)
fileObject.flush()
fileContent = fileObject.read()
print ( "\nAfter flush():\n" , fileContent)
fileObject.close()
|
Output:
Before flush():
Geeks 4 geeks!
After flush():
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
13 Jul, 2022
Like Article
Save Article