Home » Python

Python File flush() Method with Example

Python File flush() Method: Here, we are going to learn about the flush() method, how to clear/flush the internal buffer in Python?
Submitted by IncludeHelp, on December 18, 2019

File flush() Method

flush() method is an inbuilt method in Python, it is used to clear/flush the internal buffer, it is best practice while working with fila handling in Python, the internal buffer can be cleared before writing/appending the new text to the file.

Syntax:

    file_object.flush()

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is <class 'NoneType'>, it returns nothing.

Example:

# Python File flush() Method with Example

# creating a file 
myfile = open("hello.txt", "w")

# writing text to the file 
myfile.write("Hello friends, how are you?")

# flushing the internal buffer
myfile.flush()
# writing the text again
myfile.write("\nI am good, what about you?")

# flushing the internal buffer
myfile.flush()
# writing the text again
myfile.write("\nI am good too, thanks!")

# closing the file
myfile.close()

# reading content from the file
myfile = open("hello.txt", "r")
print("file content...")
print(myfile.read())
myfile.close()

Output

file content...
Hello friends, how are you?I am good, what about you?
I am good too, thanks!


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.