I stumbled onto this stackoverflow question while doing some file IO: Confused by python file mode "w+"
r
for readingw
for writingr+
opens for reading and writing (cannot truncate a file)w+
for writing and reading (can truncate a file)rb+
reading or writing a binary filewb+
writing a binary filea+
opens for appending
Note the r+
cannot truncate a file. So I was looking for something that could truncate the file after reading it which led me to another SO link: Python truncate lines as they are read
I saw that they used a different mode, rw+
, which was not documented. From how it was used in the answer, I guessed it meant "open for reading, writing and truncating but do not truncate on open".
I later tested this mode and it seems that it was removed in Python 3, hence throwing a ValueError
when used:
Python 2:
f = open("myfile.txt", "rw+")
text = f.read()
f.truncate(0)
f.close()
Python 3:
f = open("myfile.txt", "rw+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: must have exactly one of create/read/write/append mode
However, I needed a file mode in Python 3 that can truncate as well as read but not truncate on open. So, after a bit more testing, I found that r+
can actually truncate in both Python 2 and 3.
Python 2:
f = open("myfile.txt", "r+")
text = f.read()
f.truncate(0)
f.seek(0, 0)
print f.read()
f.close()
Will print out nothing.
Python 3:
f = open("myfile.txt", "r+")
text = f.read()
f.truncate(0)
f.seek(0, 0)
print(f.read())
f.close()
Will also print out nothing.
My question is, if both r+
and rw+
can truncate, what are the differences between them in Python 2?