What’s the difference between ‘r+’ and ‘a+’ when open file in python?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

One difference is for r+ if the files does not exist, it’ll not be created and open fails. But in case of a+ the file will be created if it does not exist.

Method 3

If you have used them in C, then they are almost same as were in C.

From the manpage of fopen() function : –

  • r+ : – Open for reading and writing. The stream is positioned at
    the
    beginning of the file.
  • 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. Subse-
    quent writes to the file will always end up at the then current
    end of file, irrespective of any intervening fseek(3) or similar.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x