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?