Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read from file opened in "a+" mode?

Tags:

python

io

windows

By definition, "a+" mode opens the file for both appending and reading. Appending works, but what is the method for reading? I did some searches, but couldn't find it clarified anywhere.

f=open("myfile.txt","a+")
print (f.read())

Tried this, it prints blank.

like image 832
morris Avatar asked Dec 13 '25 15:12

morris


1 Answers

Use f.seek() to set the file offset to the beginning of the file.

Note: Before Python 2.7, there was a bug that would cause some operating systems to not have the file position always point to the end of the file. This could cause some users to have your original code work. For example, on CentOS 6 your code would have worked as you wanted, but not as it should.

f = open("myfile.txt","a+")
f.seek(0)
print f.read()
like image 131
Bill Lynch Avatar answered Dec 16 '25 06:12

Bill Lynch



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!