My question is about Python build-in open
function with a+
mode. First, from this thread, I know for a+
mode, subsequent writes to the file will always end up at the current end of file. I write the following simple program to confirm this fact:
file = 'test0.txt' # any non-empty text file
with open(file, 'a+', encoding='utf-8') as f:
f.seek(0)
f.write('added')
# print(f.tell())
cc = f.readlines() # strange!
print(cc)
Yes, 'added'
is appended on the end even if forcing the stream to position at the beginning of the file by seek()
method.
I think cc
should be []
, because the stream is positioned at the end of the file. However, it is wrong! The result is:
cc
shows all the text before appending added
. Moreover, either switching to comment f.seek(0)
or switching to uncomment print(f.tell())
makes things normal: c
turns to be []
as expected. For me, this means tell()
indeed changes something—not just reporting the position—in this case. I would be very grateful if anyone could tell me the logic behind this.