pythonreadlineseektell

Python seek() not shifting pointer to right place


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!


Solution

  • you need to flush() the buffer to disk, because write is happening in the buffer in memory not the actual file on the disk.

    In the second scenario, before readline() you are calling f.tell() which is actually flushing the buffer to disk.

    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("-")
          f.flush() #------------->