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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With