Python flush method:

The flush is a method of IOBase class in Python that is used to clear the internal buffer. In other words, it clears the write buffer of a stream. Although, the close() function in Python automatically flushes the file. But, sometimes a programmer may also need to flush the file before closing it, in such scenarios he can use flush().

Method Signature

The signature for the flush method is as shown below.

fileObject.flush()

Method parameters and return type

  • Here, the flush method doesn’t take any parameters.
  • However, it doesn’t return any value.

Python flush method Examples:

Example 1: In this example, we will open a file in write mode and close it after writing. Thereafter, we will again open the same file for reading.

# creating a file 
f1 = open("test.txt", "w")

# Writing 
f1.write("Hello World")

# Flushing the internal buffer
f1.flush()
# Writing 
f1.write("\nPython Programming")

# Flushing the internal buffer
f1.flush()
# Writing 
f1.write("\nIts fun to learn Python")

# closing
f1.close()

# Opening in read mode
f1 = open("test.txt", "r")
print(f1.read())
f1.close()

Output

Hello World
Python Programming
Its fun to learn Python

Example 2: In this example, we will open a file in append mode and add the content to existing content.

# creating a file 
f1 = open("test.txt", "a")
print ("File Name ", f1.name)

# flushing the internal buffer
f1.flush()

# Writing 
f1.write("Hello World")
f1.write("\nPython Programming")
f1.write("\nIts fun to learn Python")

# closing
f1.close()

Output

File Name  test.txt

Conclusion

Hence, the flush() method clears the internal buffer to ease the writing process.

References

Happy Learning 🙂

Leave A Comment