使用Python'with'语句时捕获异常
发布于 2021-01-29 16:08:07
令我感到羞耻的是,我不知道如何处理python’with’语句的异常。如果我有代码:
with open("a.txt") as f:
print f.readlines()
我真的很想处理“找不到文件异常”以便执行某些操作。但是我不能写
with open("a.txt") as f:
print f.readlines()
except:
print 'oops'
而且不能写
with open("a.txt") as f:
print f.readlines()
else:
print 'oops'
在try / except语句中包含“ with”,否则将不起作用:不会引发异常。为了以Python方式处理“ with”语句中的失败,我该怎么办?
关注者
0
被浏览
52
1 个回答
-
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'
如果您希望通过打开调用与工作代码进行不同的错误处理,则可以执行以下操作:
try: f = open('foo.txt') except IOError: print('error') else: with f: print f.readlines()