I was trying out the following python seek()/tell() function. "input.txt" is a text file containing 6 letters, one per row:
a
b
c
d
e
f
text = " "
with open("input.txt", "r+") as f:
while text!="":
text = f.readline()
fp = f.tell()
if text == 'b\n':
print("writing at position", fp)
f.seek(fp)
f.write("-")
I was expecting the letter "c" to be overwritten as "-" but instead I got the dash appended like this although the print says "writing at position 4":
a
b
c
d
e
f-
The output is correct when I swop the readline() and the tell() ("b" will be replaced by"-"):
text = " "
with open("input.txt", "r+") as f:
while text!="":
fp = f.tell() # these 2 lines
text = f.readline() # are swopped
if text == 'b\n':
print("writing at position", fp)
f.seek(fp)
f.write("-")
Can help to explain why the former case doesn't work? Thank you!