Python

1   Overwriting existing file contents

Confused by python file mode “w+”

If you want to overwrite existing file contents from the beginning of a file, use the w+ mode and immediately write() without reading. Now, if you want to overwrite from the middle of a file, use the w+ mode, read contents, and call seek() explicitly before writing. Otherwise, write() will do append, not overwrite (cover?).

  • open(.., "w+"), write(): overwrites from the beginning
  • open(.., "w+"), read(), write(): appends at the end
  • open(.., "w+"), read(), seek(tell()), write(): overwrites from the middle

test.in

hello1
ok2
byebye3

Run

with open("test.in", 'r+')as f:
    f.readline()
    f.write("addition") # doesn't overwrite anything

test.in

hello1
ok2
byebye3
addition

Run

with open("test.in", 'r+')as f:
    f.write("overwrite") # overwrites from the beginning

test.in

overwrite2
byebye3
addition

Run

with open("test.in", 'r+')as f:
    f.readline()
    f.seek(f.tell())  # seek first
    f.write("again?") # now overwrite

test.in

overwrite2
again?3
addition