How to read from file opened in “a+” mode?

2020-06-16 02:03发布

问题:

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.

回答1:

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()


回答2:

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]: 0L

In [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.



回答3:

MODES r+ read and write Starts at the beginning of the file r read only Starts at the beginning of the file a+ Read/Append. Preserves file content by writing to the end of the file

Good Luck! Isabel Ruiz



回答4:

There are still quirks in newer version of Python dependant on OS and they are due to differences in implementation of the fopen() function in stdio.

Linux's man fopen:

a+ - Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

OS X:

``a+'' - Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

MSDN doesn't really state where the pointer is initially set, just that it moves to the end on writes.

When a file is opened with the "a" or "a+" access type, all write operations occur at the end of the file. The file pointer can be repositioned using fseek or rewind, but is always moved back to the end of the file before any write operation is carried out. Thus, existing data cannot be overwritten.

Replicating the differences on various systems with both Python 2.7.x and 3k are pretty straightforward with .open .tell

When dealing with anything through the OS, it's safer to take precautions like using an explicit .seek(0).