Does Python automatically flush its buffer when invoking search and / or read operations after writing?

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 hello to a file. Of course, two buffers are involved here - the internal Python buffer and the operating system buffer, so "hi" cannot actually be written to the file. I understand that if I explicitly cleaned the file with file.flush() or closed 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 that in both cases (when I explicitly call flush or close), there is no guarantee that the operating system will actually write to disk (to guarantee this, I would have to call os.fsync(file) ).

In any case, in the above code, I do not call flush and do not close. So here is 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 Python guaranteed to file.read() its own buffer? If this is guaranteed, is the guaranteed flash the result of a search operation, a read operation, or any of them? In other words, search and / or read to automatically flash? And in order to be clear, I'm not talking about the fact that the operating system is installed on the disk, which is pretty positive, not guaranteed - I'm talking only about the Python stream of its own buffer.

When I tested this, it seemed that both reads and searches dropped the Python buffer, but I'm not sure if this is just a possible behavior or guaranteed behavior.

If this is not guaranteed behavior, can I still rely on calling file.seek or file.read after file.write (i.e. Python has another internal mechanism to solve this issue that is not related to OS writing )? Or is it best to always call file.flush() before searching or reading that follows the record?

+5
source share

Source: https://habr.com/ru/post/1262707/


All Articles