Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch exception happening during Context Manager - Python [duplicate]

Possible Duplicate:
Using python “with” statement with try-except block

I'm using open to open a file in Python. I encapsulate the file handling in a with statement as such:

with open(path, 'r') as f:
    # do something with f
    # this part might throw an exception

This way I am sure my file is closed, even though an exception is thrown.

However, I would like to handle the case where opening the file fails (an OSError is thrown). One way to do this would be put the whole with block in a try:. This works as long as the file handling code does not throw a OSError.

It could look something like :

try:
   with open(path, 'rb') as f:
except:
   #error handling
       # Do something with the file

This of course does not work and is really ugly. Is there a smart way of doing this ?

Thanks

PS: I'm using python 3.3

like image 380
paul Avatar asked Dec 17 '25 22:12

paul


1 Answers

Open the file first, then use it as a context manager:

try:
   f = open(path, 'rb')
except IOError:
   # Handle exception

with f:
    # other code, `f` will be closed at the end.
like image 131
Martijn Pieters Avatar answered Dec 19 '25 11:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!