3

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

Community
  • 1
  • 1
paul
  • 1,212
  • 11
  • 15

1 Answers1

12

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.
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @paul: Then accept this answer (and up-vote it too if you think it's worthy). – martineau Nov 18 '12 at 14:42
  • here f will b out of scope . .I.e with cannot access 'f' – Sandeep Das Feb 10 '16 at 09:59
  • @SandeepDas: I've assumed that handling the request means you'll exit the function or otherwise not continue with using `f` as a context manager. You can use an `else:` block here (part of the `try:` statement) if you are not exiting. – Martijn Pieters Feb 10 '16 at 10:27