Fix Python – Catching an exception while using a Python ‘with’ statement

Question

Asked By – grigoryvp

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 neither, and an exception is not raised. What can I do in order to process failure inside with statement in a Pythonic way?

Now we will see solution for issue: Catching an exception while using a Python ‘with’ statement


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()

This question is answered By – Douglas Leeder

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0