Python - File flush() Method
The Python flush() method is used to flush out the internal buffer. When a file is closed, Python automatically flushes out the internal buffer. This method is useful when the flushing of the internal buffer is needed while the file is open. Please note that this method may be a no-op on some file-like objects.
Syntax
file.flush()
Parameters
No parameter is required.
Return Value
None.
Example: Flush internal buffer
In the example below, Python file flush() method is used to flush the internal buffer.
MyFile = open("test.txt", "w+") MyFile.write("This is a demo content.") #sets the offset position to the beginning MyFile.seek(0) #read content before closing the file print("Name of the file:", MyFile.name) print(MyFile.read()) #flushing the internal buffer MyFile.flush() #closing the open file MyFile.close()
The output of the above code will be:
Name of the file: test.txt This is a demo content.
❮ Python File Handling Methods