File flush python – Python File flush() Method with Examples

File flush() Method in Python:

File flush python: The flush() function is a built-in method in Python that is used to clear or flush the internal buffer. When working with fila handling in Python, it is recommended practice to clear the internal buffer before writing or appending new text to the file.

Syntax:

file.flush()

Parameters: This method has no arguments.

Return Value:

Python file flush: This method’s return type is <class ‘NoneType’>, which means it returns nothing.

File flush() Method with Examples in Python

Approach:

  • Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
  • Open the file in write mode. In this case, we’re writing the contents into the file.
  • Write some random text into the given file using the write() function.
  • Apply flush() method to the given file(It clears the internal buffer).
  • Again write some random text into the given file using the write() function.
  • Apply flush() method to the given file(It clears the internal buffer).
  • Close the given file using the close() function.
  • Open the file in read-only mode. In this case, we’re simply reading the contents of the file.
  • Print the content of the given file using the read() function.
  • Close the given file using the close() function.
  • The Exit of the Program.

Below is the implementation:

# Make a single variable to store the path of the file. This is a constant value.
# This value must be replaced with the file path from your own system in the example below.
givenFilename = "samplefile.txt"
# Open the file in write mode. In this case, we're writing the contents into the file.
gvn_file = open(givenFilename, 'w') 
# Write some random text into the given file using the write() function
gvn_file.write("Hello this is btechgeeks\n")
# Apply flush() method to the given file(It clears the internal buffer)
gvn_file.flush()
# Again write some random text into the given file using the write() function
gvn_file.write("good morning btechgeeks")
# Apply flush() method to the given file(It clears the internal buffer)
gvn_file.flush()
# Close the given file using the close() function
gvn_file.close()

# Open the file in read-only mode. In this case, we're simply reading the contents of the file.
gvn_file = open(givenFilename, 'r') 
# Print the content of the given file using the read() function
print("The given file content:")
print(gvn_file.read())
# Close the given file using the close() function
gvn_file.close()

Output:

The given file content:
Hello this is btechgeeks
good morning btechgeeks

File Content:

Hello this is btechgeeks
good morning btechgeeks