50

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

cs95
  • 379,657
  • 97
  • 704
  • 746
Tanky Woo
  • 4,906
  • 9
  • 44
  • 75

3 Answers3

81

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

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 5
    The official documentation implies that the "forget seek" behavior is actually not guaranteed (it works with "*some*" Unixes): http://docs.python.org/2/library/functions.html#open. So, `a+` does *not* exactly work in the same way as in C. – Eric O. Lebigot Nov 06 '12 at 09:33
  • I would suggest that you edit the answer to reflect both the fact that the modes do *not* work exactly in the same way as in C, and the fact that the output is not necessarily appended to the end of the file (albeit it is when no seek is done). – Eric O. Lebigot Nov 06 '12 at 09:40
  • 1
    @EOL Well, I must agree here, but still I'm not sure that `fopen` that implies the pythonic function do not have the same behavior in *some* Unixes. However, since `open` function have additional modes (`U`, `rU`) we can add "*almost*" to the answer. – VisioN Nov 06 '12 at 09:50
  • 1
    @EOL Doesn't Python rely on system's C libraries for this? I would assume same behavior. – Janne Karila Nov 06 '12 at 09:55
  • @JanneKarila: Good question. :) I would indeed guess that CPython does rely on the system's C libraries. I am not sure about other Python implementations, though (Jython, PyPy,…). – Eric O. Lebigot Nov 07 '12 at 01:47
8

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.

codaddict
  • 445,704
  • 82
  • 492
  • 529
6

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. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.
Evg
  • 25,259
  • 5
  • 41
  • 83
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525