令我遗憾的是,我无法弄清楚如何处理python'with'语句的异常.如果我有一个代码:
with open("a.txt") as f:
print f.readlines()
Run Code Online (Sandbox Code Playgroud)
我真的想处理'文件未找到异常'以便进行处理.但我不能写
with open("a.txt") as f:
print f.readlines()
except:
print 'oops'
Run Code Online (Sandbox Code Playgroud)
并且不能写
with open("a.txt") as f:
print f.readlines()
else:
print 'oops'
Run Code Online (Sandbox Code Playgroud)
在try/except语句中包含'with'不起作用:不引发异常.为了以Pythonic方式处理'with'语句内部的失败,我该怎么办?