问题
Suppose I want to change the first two characters of the second line of the text file text_file
to XX
.
Say text_file
has contents:
line1
line2
line3
I wrote the following script to accomplish the task:
f = open('text_file', 'r+')
f.readline()
f.write('XX')
f.close() # this flushes changes to disk implicitly
When I run this code in Python 2.7.9, this works fine, altering text_file
so that it becomes:
line1
XXne2
line3
However, when I run it in Python 3.4.3, text_file
ends up having these contents:
line1
line2
line3
XX
Now, if I alter the code like this:
f = open('text_file', 'r+')
f.readline()
f.seek(f.tell()) # shouldn't this be doing nothing?
f.write('XX')
f.close() # this flushes changes to disk implicitly
And run it in Python 3.4.3, the results are as desired.
I seriously don't understand what's going on here: why does write()
start writing at that unexpected position[*]? And seeking to the current position isn't supposed to be changing anything, right?
Hope somebody can shed some light on this for me, thanks!
UPDATE: It's probably worth mentioning the OS I'm using. It's Xubuntu 15.04, Linux kernel 3.19.
UPDATE 2: As suggested by @cdarke, opening in binary mode rb+
(and accordingly writing binary strings) makes the script work in Python 3.4.3 without the use of seek
as I did above. Why does this work, and not my original way?
(*): NOTE: That it starts writing at the end of the buffer is a matter of coincidence. I know this because the actual text file I'm working with is much larger, and there it didn't start writing at the end of the buffer.
来源:https://stackoverflow.com/questions/40552106/file-object-methods-write-or-writelines-start-writing-at-unexpected-position