Eye of Hell Eye of Hell - 2 months ago 12
Python Question

Catching an exception while using a Python 'with' statement

To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:

with open("a.txt") as f:
print f.readlines()


I really want to handle 'file not found exception' in order to do somehing. But I can't write

with open("a.txt") as f:
print f.readlines()
except:
print 'oops'


and can't write

with open("a.txt") as f:
print f.readlines()
else:
print 'oops'


enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?

Answer
from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'

If you want different handling for errors from the open call vs the working code you could do:

try:
    f = open('foo.txt')
except IOError:
    print('error')
else:
    with f:
        print f.readlines()
Comments