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?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…