Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #74159
| Newsgroups | comp.lang.python |
|---|---|
| Date | 2014-07-08 02:38 -0700 |
| References | <mailman.11616.1404796682.18130.python-list@python.org> |
| Message-ID | <97efde28-a8c8-44cd-817a-97fab21876cb@googlegroups.com> (permalink) |
| Subject | Re: error handling when opening files |
| From | wxjmfauth@gmail.com |
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.
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
error handling when opening files Alex Burke <alexjeffburke@gmail.com> - 2014-07-08 01:49 +0200
Re: error handling when opening files Marko Rauhamaa <marko@pacujo.net> - 2014-07-08 11:30 +0300
Re: error handling when opening files Steven D'Aprano <steve@pearwood.info> - 2014-07-08 09:00 +0000
Re: error handling when opening files Chris Angelico <rosuav@gmail.com> - 2014-07-08 20:35 +1000
Re: error handling when opening files Alex Burke <alexjeffburke@gmail.com> - 2014-07-09 21:59 +0200
Re: error handling when opening files wxjmfauth@gmail.com - 2014-07-08 02:38 -0700
csiph-web