Question

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

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top