File pointer position in file handling

269 Views Asked by At
f=open("hello.txt","r+")
f.read(5)
f.write("op")
f.close()

the text file contains the following text:

python my world heellll mine

According to me after opening the file in r+ mode the file pointer is in beginning(0). After f.read(5) it will reach after o.and then after f.write("op") it will "n " with "op" and the final output will be:

pythoopmy world heellll mine

but on running the program the output is:

python my world heellll mineop

Please help and explain why it is happening.

2

There are 2 best solutions below

2
jpa On

Python enables file buffering by default, and in fact requires it for text files read in UTF-8 encoding. This means that at least a complete line is read from the input file, even if the user code requests less bytes.

By accessing the file in binary mode and switching off buffering, it works as you expect:

f=open("hello.txt","rb+", buffering = 0)
f.read(5)
f.write(b"op")
f.close()
0
Marcelo Paco On

An alternative method is using seek() method to get your desired result:

f=open("hello.txt","r+")
f.seek(5)
f.write(b"op")
f.close()

hello.txt contents:

pythoopmy world heellll mine