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.
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 a means writing file, append mode; a+ means reading and writing file, append mode.
In Python, why is 'r+' but not 'rw' used to mean "read & write"?
This is also the default mode in which a file is opened. Read and Write ('r+'): Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exist.
Python copies the modes from C's fopen()
call. r+
is what C uses, and Python stuck with the 40-year-old convention.
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