Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File pointer position in file handling

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.

like image 929
om bahetra Avatar asked Jul 02 '26 09:07

om bahetra


1 Answers

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()
like image 100
jpa Avatar answered Jul 04 '26 22:07

jpa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!