Python の 'with' ステートメントの使用中に例外をキャッチする 質問する

Python の 'with' ステートメントの使用中に例外をキャッチする 質問する

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 ステートメントで囲むこともできず、例外は発生しません。ステートメント内の失敗を Python の方法でwith処理するにはどうすればよいでしょうか?with

ベストアンサー1

このソリューションでは、with-block-code を try-except 節の外側に保持します。

try:
    f = open('foo.txt')
except FileNotFoundError:
    print('error')
else:
    with f:
        print f.readlines()

おすすめ記事