How to flush the internal buffer in Python?

PythonServer Side ProgrammingProgramming

Python buffers writes to files. That is, file.write returns before the data is actually written to your hard drive. The main motivation of this is that a few large writes are much faster than many tiny writes, so by saving up the output of file.write until a bit has accumulated, Python can maintain good writing speeds.

file.flush forces the data to be written out at that moment. To flush contents you wrote actually to the file, use:

with open("my_file.txt", "w+") as file:
    file.write("foo")
    file.write("bar")
     file.flush()
raja
Published on 22-Dec-2017 10:57:47
Advertisements