The problem has to do with buffered IO.
the open() function seems to open a buffered file handle.
So in fact whenever something from the file is read, at least an entire buffer is read in which seems to be on my machine about 8k (8192) bytes.
This is for optimizing performance.
So readline will read one block return the first line and keep the rest in a buffer for potential future reads.
f.tell() gives you the position relative to the bytes, that were already returned by readline().
This you can force the write pointer with f.seek(f.tell())
to the place, that you intended. Without the explicit seek statement you will write after the buffer.
Use following script to illustrate and look at the output:
You will see, that I tried to play with the buffering
parameter.
Accordin to the doc 1 means line buffering, but I don't see any change in behavior.
with open("file", "w") as f:
f.write(("*" * 79 +"\n") * 1000)
with open('file', 'r+', buffering=1) as f:
print(f.tell())
print(f.readline().strip())
print(f.tell())
# f.seek(f.tell())
f.write('Hello')
print(f.tell())
print("----------- file contents")
with open("file", "r") as f:
pass
print(f.read())
print("----------- END")
So if you write after a readline(), then it will write the new data after the buffer, that's read in.
f.tell() on the other hand returns you the position, that tells you how many bytes were already returned.
The output will be:
0
*******************************************************************************
80
8197
8202
----------- file contents
*******************************************************************************
*******************************************************************************
...
*******************************************************************************
********************************HelloHello*************************************
*******************************************************************************
*******************************************************************************
*******************************************************************************
*******************************************************************************
...