Python File flush() Method – Tutorial with Examples

Python File flush() Method

The flush() method in Python is a built-in method used to write any data from the buffer to the file. This method is useful when we want to ensure that all the data in the buffer is written to the file before continuing with the program.

Syntax

file.flush()

Return Value

The flush() method does not return anything.

Examples

Example 1: Basic Usage

In this example, we will create a file, write some data to it, and then flush the buffer using the flush() method:

file = open("example.txt", "w")
file.write("Hello, World!")
file.flush()

In this example, we opened a file named “example.txt” in write mode, wrote the string “Hello, World!” to the file, and then flushed the buffer using the flush() method.

Example 2: Writing Large Data

If we are writing a large amount of data to a file, we may want to use the flush() method to write the data to the file in smaller chunks:

file = open("example.txt", "w")
for i in range(100000):
    file.write(str(i) + "\n")
    if i % 1000 == 0:
        file.flush()
file.close()

In this example, we opened a file named “example.txt” in write mode, and then wrote 100,000 lines to the file using a loop. Every 1,000 lines, we flush the buffer using the flush() method. This ensures that the data is written to the file in smaller chunks, which can improve performance.

Example 3: Writing to a Network Stream

The flush() method can also be useful when writing to a network stream:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('www.google.com', 80))
s.send(b"GET / HTTP/1.0\n\n")
response = s.recv(4096)
print(response.decode())
s.close()

In this example, we use the socket module to connect to the Google website and retrieve the HTTP response. After sending the request, we call the flush() method to ensure that all the data is sent to the server before attempting to receive the response.

Use Cases

The flush() method can be useful in situations where we want to ensure that all the data in the buffer is written to the file before continuing with the program. This can be particularly important when working with network streams or large files. Additionally, the flush() method can be used to improve performance when working with large files, by allowing us to write data to the file in smaller chunks.

Conclusion

The flush() method is a useful tool for ensuring that data is written to a file before continuing with the program. By using this method, we can avoid situations where data is lost due to buffering or other issues. Whether we are working with small or large files, or with network streams, the flush() method can help ensure that our data is written to the file correctly and improve performance. It is an essential method for anyone working with file I/O in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *