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

jpa
  • 10,351
  • 1
  • 28
  • 45
om bahetra
  • 41
  • 4

2 Answers2

1

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()
jpa
  • 10,351
  • 1
  • 28
  • 45
  • Plz explain buffering as being a school student,i am not aware about it and exaplain reason in simple language. – om bahetra May 05 '23 at 15:36
  • @ombahetra Reading each byte separately from input file is slow. Python tries to be helpful and read up to a few thousand bytes ahead of time, so it is faster each time you run `read()` function. – jpa May 05 '23 at 16:00
0

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
Marcelo Paco
  • 2,732
  • 4
  • 9
  • 26