Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird file seeking behaviour

Tags:

python

With respect to two interactions below, I'd expect the same file output by both, but the second one writes at the end of the file. The only difference is a read statement AFTER the write, I don't understand what's happening. What am I missing?

Expected behavior:

>>> f = open("test.txt","w+")
>>> f.write('0123456789')
10
>>> f.seek(0)
0
>>> f.read(3)
'012'
>>> f.seek(0,1)
3
>>> f.write('XX')
2
>>> f.seek(0)
0
>>> f.read()
'012XX56789'
>>> f.close()

Unexpected behavior:

>>> f = open("test.txt","w+")
>>> f.write('0123456789')
10
>>> f.seek(0)
0
>>> f.read(3)
'012'
>>> f.seek(0,1)
3
>>> f.write('XX')
2
>>> f.read(2)
'34'
>>> f.seek(0)
0
>>> f.read()
'0123456789XX'
>>> f.close()

As you can see XX was written after the whole line, while I was at position 3 when writing these characters.

like image 314
Markus Steiner Avatar asked Sep 02 '19 11:09

Markus Steiner


1 Answers

What happened was that the write was buffered, and the intervening read advanced the underlying file position to the end of the file (since it’s small) before the write was committed (flushed). If what follows the write is a seek, the write buffer is committed (to the right place) before actually seeking. This approach avoids overhead on every read to check for pending writes and has long been specified by POSIX.

like image 188
Davis Herring Avatar answered Nov 09 '22 07:11

Davis Herring