Reputation: 41
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.
Upvotes: 0
Views: 26
Reputation: 27211
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)
Upvotes: 0