error handling when opening files
wxjmfauth at gmail.com
wxjmfauth at gmail.com
Tue Jul 8 05:38:42 EDT 2014
Alex is right (at least not wrong) and I'm also working
in a similar way.
- If there is a problem in opening, the file is never
opened and only an IOError can happen.
- If do_stuff succeeds: the file is open and will be closed
because of the with statement.
- If do_stuff does not succeed (errors), the file will be
closed (with statement) and only later the error is raised.
Tricky, but it works like this.
In short: simple and elegant solution.
>>> def z():
... try:
... with open('eta.cfg', 'r') as f:
... a = 1 / 0
... except IOError:
... print('error in opening file')
... except ZeroDivisionError:
... print('ZeroDivisionError', f.closed)
...
>>> z()
ZeroDivisionError True
>>> def z2():
... try:
... with open('xxx.cfg', 'r') as f:
... a = 1 / 0
... except IOError:
... print('error in opening file')
... except ZeroDivisionError:
... print('ZeroDivisionError', f.closed)
...
>>> z2()
error in opening file
>>> def z3():
... try:
... with open('xxx.cfg', 'r') as f:
... a = 1 / 0
... except IOError:
... print('error in opening file')
... print(f.closed)
... except ZeroDivisionError:
... print('ZeroDivisionError', f.closed)
...
>>> z3()
error in opening file
Traceback (most recent call last):
File "<eta last command>", line 1, in <module>
File "<eta last command>", line 7, in z3
UnboundLocalError: local variable 'f' referenced before assignment
----
One could consider a case where do_stuff is opening a file...
----
Quote: "Interestingly, did you know that even *closing* "
a file can fail?
Answer: Does "with" fail? I never explicitely closed the file.
More information about the Python-list
mailing list