tanakahdaのプログラマ手帳

プログラミングとかソフトウェア開発とかの備忘録

テキスト読み込み@Python

レガシーな書き方

/data/data.txt

Hello World!
file = open("./data/data.txt")
text = file.read()
file.close()
print(text)
Hello World!

with open()の書き方

# with open()構文でファイルを開くと、ファイルの入出力が、構文内だけで実行される
# 明示的にファイルオープンが完了するので、閉じ忘れの心配がない。
with open("./data/data.txt") as file:
    print(file.read())