I have try r+
and a+
to open file and read and write, but 'r+' and 'a+' are all append the str to the end of the file.
So, what's the difference between r+
and a+
?
Add:
I have found the reason:
I have read the file object and forgot to seek(0) to set the location to the begin
The r means reading file; r+ means reading and writing the file. The w means writing file; w+ means reading and writing the file.
The r+ mode for opening a file is similar to r mode but has some added features. It opens the file in both read and write mode. If the file does not exist with w+, the program creates new files to work on it.
a - opens a file in append mode. r+ - opens a file in both read and write mode. a+ - opens a file in both read and write mode. w+ - opens a file in both read and write mode.
w+ : Opens a file for writing and reading. wb+ : Opens a file for writing and reading in binary mode. a : Opens a file for appending new information to it. The pointer is placed at the end of the file.
Python opens files almost in the same way as in C:
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
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 appended to the end of the file (but in some Unix systems regardless of the current seek position).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With