Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between 'r+' and 'a+' when open file in python? [duplicate]

Tags:

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

like image 345
Tanky Woo Avatar asked Nov 06 '12 09:11

Tanky Woo


People also ask

What does R mean in Python Open file?

The r means reading file; r+ means reading and writing the file. The w means writing file; w+ means reading and writing the file.

What is similar between opening a file for R mode and R+ mode?

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.

What is the difference between the file opening modes R+ and W+?

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.

What is the difference in file opening mode A and W?

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.


1 Answers

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

like image 199
VisioN Avatar answered Sep 21 '22 04:09

VisioN