3

i am trying to perform both read and write operations in a python text file by opening it into r+ mode. However, irrespective of how many characters i read (say 'fo.read(5)') before performing performing the write operation (say 'fo.write("random")'), the text is written/appended at the end of the file.

fo = open("C:/Users/Dell/Desktop/files/new.txt",'r+')
fo.read(5)
fo.write('random')
fo.close()

i expected the text being written ('random' in this example) to be written 6th character onward but instead got written/appended at the end of the text file. what can be the possible explanation for this behaviour?

blhsing
  • 91,368
  • 6
  • 71
  • 106

1 Answers1

2

This definitely looks like a bug.

A workaround is to explicitly seek the current file position before you write:

fo = open("C:/Users/Dell/Desktop/files/new.txt",'r+')
fo.read(5)
fo.seek(fo.tell())
fo.write('random')
fo.close()

EDIT: As noted by @Blckknght, this is a known issue rooted from the C-level implementation of Windows. You can refer to Beginner Python: Reading and writing to the same file for references and discussions, although that linked question pertains to Python 2, where the behavior of the same code is different (the write either does nothing or produces an OSError).

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • I believe this is documented (mis-)behavior. On some platforms, it's undefined what happens if you both `read` and `write` a file without putting a `seek` in between. – Blckknght Apr 05 '19 at 17:13
  • Thanks. I've found the prior discussions and have updated my answer accordingly. I'm not marking this question as a duplicate only because that question is for Python 2, where the behavior is different. – blhsing Apr 05 '19 at 17:59