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.
Such examples are very implementation-dependent and if you are looking to get an exact answer, you have to dive deep into the source code.
Indeed you are trying to get an undesired outcome using the methods in an undesired order. I know I am not providing a solution here as to why this happens, but here are some of the questions asked before and they still don't really have the detailed explanation you seek.
All in all, be my guest, go ahead read the source code, understand what happens under to hood and explain us what the issue is. If you think this would take a lot of time (I know from experience), use the methods in the order as they should be and avoid ambiguities and undesired behaviors. Like @Blckknght says, don't play with fire unless you are willing to put it out.
At the end of the day, this might actually be a security problem or not if inspected closely, though I doubt since you are not overflowing anything or overwriting to unexpected places, as there are various checks and controls for such operations.
Weird file seeking behaviour
Python 3 tell() gets out of sync with file pointer in append+read mode