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