How to read from file opened in "a+" mode?
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()
when you open the file using f=open(myfile.txt,"a+")
, the file can be both read and written to.
By default the file handle points to the start of the file,
this can be determined by f.tell()
which will be 0L
.
In [76]: f=open("myfile.txt","a+")In [77]: f.tell()Out[77]: 0LIn [78]: f.read()Out[78]: '1,2\n3,4\n'
However, f.write
will take care of moving the pointer to the last line before writing.