ファイル操作: 読み書きの基本

with 文で安全に。pathlib でモダンに。

with
コンテキストマネージャ。自動クローズ。
モード
r=読み取り, w=書き込み, a=追記。
pathlib
オブジェクト指向パス操作。

ファイル操作基礎

図書館の本の貸し出し (Library Checkout)

ファイル操作は図書館での「貸し出し」と同じです。①本棚から取り出し(open)、②読み書きし(read/write)、③必ず元の場所に戻す(close)必要があります。戻し忘れると、次の人が借りられなくなります(ファイルロック)。`with` 文は「読み終わったら自動で棚に戻してくれる」魔法の召使いです。

Pythonでファイルを扱うときは、必ず `with` 文を使います。これを使えば、エラーが起きてもプログラムが終了しても、確実に `close()` が呼ばれます。手動で `close()` を書くのは、トイレの電気を消し忘れるようなものです。

Read & Write
# ファイル読み込み
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # 全体を読む
# lines = f.readlines() # 行ごとのリスト
# ファイル書き込み
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
# 追記モード
with open("log.txt", "a", encoding="utf-8") as f:
f.write("New log entry\n")
Bad
# ❌ Bad: close() を忘れる可能性
f = open("data.txt")
content = f.read()
f.close() # 例外時に実行されない
Good
# ✅ Good: with 文で自動クローズ
with open("data.txt") as f:
content = f.read()
# 自動で close()

高度な操作

Line-by-line, pathlib
# 行ごとに処理(メモリ効率的)
with open("large.txt") as f:
for line in f:
process(line.strip())
# バイナリファイル
with open("image.png", "rb") as f:
data = f.read()
# pathlib(推奨)
from pathlib import Path
path = Path("data") / "file.txt"
text = path.read_text(encoding="utf-8")
path.write_text("content", encoding="utf-8")
# 存在確認
if path.exists():
print(path.is_file())
Tip: 大きなファイルは for line in f で1行ずつ処理。

合格ライン

with open() を使える
pathlib を使える

演習課題

課題1: with open()
with open() でファイルを読み書きしてください。
課題2: pathlib
pathlib でパスを操作してください。