mistermarko
mistermarko

Reputation: 305

Why can't I specify how a file is opened?

Consider the following code:

try:
    f = open("myfile2.dat", "rb")
except IOError:
    f = open("myfile2.dat", "ab+")
print(f.mode)
f.close()

If myfile2.dat doesn't exist when I run this code Idle opens a new file with rb+ not ab+, why?

Upvotes: 1

Views: 113

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122222

You are opening a new file in append + write mode. Because there is no file to append to, you get one in read + write mode instead.

This is essentially the same thing. There is no problem here, you can still both read from and write to the file.

Under the hood, the file is still open in append mode, but the .mode attribute gives a simpler view on the file; it merely will report what you can do with the file now, not what happened when you opened the file. It shows only if you can read or write the file and if the file was opened for exclusive creating (x mode).

See the C code for the .mode attribute.

Update: Yes, this is confusing, and really a bug. The path to fix this discrepancy has recently been merged into Python, and when new releases of Python 2.7, 3.3 and 3.4 come out file objects' .mode attribute will better reflect the original mode string used to open the file.

Upvotes: 4

Jack Leow
Jack Leow

Reputation: 22487

Edit: Disregard this, this was done on Python 2.x, I did not see the #python-3.x tag in the original question.

It opened ab+ for me:

>>> try:
...     f = open("myfile2.dat", "rb")
... except IOError:
...     f = open("myfile2.dat", "ab+")
... 
>>> print(f.mode)
ab+

This is running Jython on a Mac.

Upvotes: 0

Related Questions