Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected read/write behaviour in 'r+' mode in python text files

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?

like image 543
Singularity Avatar asked Aug 13 '26 13:08

Singularity


1 Answers

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).

like image 140
blhsing Avatar answered Aug 16 '26 02:08

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!