File pointer postion

27 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 explain why it is happening in simple language.

If any complicated term is involved in explaination please exaplain the term.

1

There are 1 answers

1
SIGHUP On

Rather than reading a number of characters (bytes) you can just seek to the appropriate offset. Write your data then seek to EOF before closing as follows:

import os

with open('hello.txt', 'r+') as data:
    data.seek(5, os.SEEK_SET)
    data.write('op')
    data.seek(0, os.SEEK_END)