ファイル読み込み

ファイルを読み込む際、ファイルオープンの際にエラーが起きたときを考えると、以下のように書くべきではない。

try:
     file_object = open(file)
     print file_object.read()
finally:
     file_object.close()


このような場合、file_objectをtry句の外に出してしまうのが適切な方法である。

file_object = open(file)
try:
     print file_object.read()
finally:
     file_object.close()

Python クックブック 第2版

Python クックブック 第2版