Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python automatically flush its buffer when calling seek and/or read operations following a write?

Tags:

python

Let's say I write the following python code:

file = open("test.txt","w+")
file.write("hi")
file.seek(0)
file.read()

The second line tells Python that I want to write "hi" to file. Of course there are two buffers involved here - the internal Python buffer and the operating system buffer - so "hi" may not actually be written to the file. I understand that if I explicitly flush the file with file.flush() or close the file with file.close() then the Python buffer will be cleared and Python will use the operating system API write method. I also understand, in both those cases (where I explicitly call flush or close), there's no guarantee that the operating system will actually write to the disk (to guarantee this I'd have to call os.fsync(file)).

Anyway, in the code above, I do not call flush nor close. So here's my question:

After the write operation, when I return the file pointer to the beginning of the file (file.seek(0)) and/or read from the file (file.read()), is it guaranteed that Python will flush its own buffer? If this is guaranteed, is the guaranteed flush a result of the seek operation, read operation, or either? In other words, do seek and/or read automatically perform a flush? And just to be clear, I'm not talking about the operating system flush to disk, which I'm pretty positive is not guaranteed - I'm only talking about Python's flush of its own buffer.

When I tested this, it seemed that both the read and seek did flush Python's buffer, but I'm not sure if this is just possible behavior, or guaranteed behavior.

If this is not guaranteed behavior, can I still rely on calling file.seek or file.read after a file.write (ie/ does Python have some other internal mechanism for dealing with this that does not involve an OS write)? Or is it best practice to always call file.flush() before a seek or read that follows a write?

like image 389
VKK Avatar asked Jan 31 '26 04:01

VKK


1 Answers

For specifically CPython, for buffered IO seek calls the _io__Buffered_seek_impl which is guaranteed to flush if and only if the whence argument is set to SEEK_END (2)

read with zero arguments calls _bufferedreader_read_all through _io__Buffered_read_impl, which does flush.

like image 143
avayert Avatar answered Feb 01 '26 19:02

avayert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!