使用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 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。
    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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看