File flush() method in Python
Python allows users to manage files by using the concept of file handling. A user can open, read, write, manipulate files and can perform many other file handling operations to a file. One of these file handling operations is the file flush() method in Python.
File flush() method –
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.
This method does not require any parameters and it does not return anything.
Now let us look at the below example which illustrates the use of flush() method. Before going through the program a text file gfg.txt is created having the below content.
Geeks 4 geeks!
In the above program, the gfg.txt is opened in read 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.
Now let us look at another example which demonstrates the use of the flush() method.
Before flush(): Geeks 4 geeks! After flush():
In this program initially, we create 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 fileObject reads nothing and fileContent remains an empty variable. Hence nothing is displayed after flush() method.