yaobin
yaobin

Reputation: 2526

In Python, why is 'r+' but not 'rw' used to mean "read & write"?

In Python, when opening a file, we use 'r' to indicate read-only and 'w' write-only. Then we use 'r+' to mean "read and write".

Why not use 'rw'? Doesn't 'rw' looks more natural than 'r+'?


Edit on Jan. 25th:

Oh.. I guess my question looks a little confusing.. What I was trying to ask is: 'r' is the first letter of 'read' and 'w' the first letter of 'write' so 'r' and 'w' look natural to map to 'read' and 'write'. However, when it comes to 'read and write', Python uses 'r+' instead of 'rw'.

So the question is actually about the naming rationale instead of the behavior differences between them.

Upvotes: 25

Views: 16732

Answers (3)

ha9u63a7
ha9u63a7

Reputation: 6824

This is what happens:

>>> f1 = open("blabla.txt", 'rw');
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:18:40) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f1=open("blabla.txt",'rw')
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    f1=open("blabla.text",'rw')
ValueError: must have exactly one of create/read/write/append mode

It's just how the read/write/append function is configured in core python. Some will say that it has to do with old c-style fopen() directives r w r+ etc.

Upvotes: 0

GLHF
GLHF

Reputation: 4035

Don't took it as pure English, r+ means read extended actually, Python!=English. All of the languages has basic rules, and @John Kugelman mentioned, Python stuck with old.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361739

Python copies the modes from C's fopen() call. r+ is what C uses, and Python stuck with the 40-year-old convention.

Upvotes: 39

Related Questions