したがって、with
キーワードをPythonで正しく使用する方法を読んでいましたが、withステートメント内で発生する可能性のある例外を処理する最善の方法を見つけられませんでした。だから私はファイルに値を書き込むための非常に簡単なスクリプトを書いています。withブロック内で例外を処理する方法
json = loads(response.read())
try:
with open(args.file, 'w') as t:
try:
t.write(json[TOKEN])
print "Wrote token to {file!s}".format(file=args.file)
except KeyError:
print "Unable to find {token!s} in response".format(token=TOKEN)
except IOError as bad:
print "Ran into an error while trying to open file {file!s}".format(file=args.file)
print "{err!s}".format(bad.message)
私は、KeyErrorがファイルがまだ適切に閉じることが検出された場合、確実にしたいと思います。
「[python」とは何のために設計されていますか?](https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for) – bgse
"私は、KeyErrorがファイルがまだ適切に閉じることがわかっているかどうかを確かめたい」 - あなたの現在のコードで*閉鎖されないと思いますか? – user2357112