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