file.flush()
时间: 2023-09-29 11:02:42 浏览: 44
The `flush()` method in Python is used to write any pending data from the buffer to the file. When a file is opened, data is not immediately written to the file. Instead, it is stored in a buffer until the buffer is full or the file is closed.
The `flush()` method forces the buffer to be written to the file. This is useful when you need to ensure that all data is written to the file before continuing with other operations.
Here's an example:
```
# Open a file for writing
file = open("example.txt", "w")
# Write some data to the file
file.write("Hello, world!")
# Flush the buffer to ensure the data is written to the file
file.flush()
# Close the file
file.close()
```
In this example, the `flush()` method is called after writing data to the file. This ensures that the data is written to the file immediately, rather than waiting for the buffer to fill up or the file to be closed.