パス、エンコーディング、安全なファイル読み取り
支援は、予測と観察した証拠を記録した後にのみ許可される。
Prerequisites
前のアクティビティを完了していること。行き詰まったら、記載の回復リンクを使う。
Learning Objective
with ブロック内で UTF-8 エンコーディングを明示してテキストファイルを読み、空でない行を数える。実行前に行数を予測し、相対パスがカレントワーキングディレクトリに依存する理由を説明する。
Instructions
参照資料: この活動に割り当てられた既存の読解・練習時間内で、Automate the Boring Stuff with Python, 3rd edition の Chapter 10; Practice Questions; Appendix B answers を参照し、ローカル課題とのつながりを一つ自分の言葉で説明する。既存の演習と合格基準は維持し、外部資料が開けない場合は本コース独自の説明を使う。新しいディレクトリに notes.txt を作り、ちょうど3行 alpha、beta、gamma を書く。open("notes.txt") のような相対パスは、スクリプトのあるフォルダではなく Path.cwd() 基準で解決される。ファイルオブジェクトを反復すると1行ずつ得られ、各行は末尾の "\n" を保持する。ただし最終行だけは例外になりうる:ファイルが改行で終わっていなければ最終行に改行は付かない("alpha\nbeta\ngamma" と書いたファイルの最終行は 'gamma')。line.strip() がその改行と前後の空白を取り除くので、空行かどうかは strip() で判定できる。with ブロックは定義済みのクリーンアップで、読み取りが例外を起こしてもファイルを閉じる。
Practice & Prediction Log
count = 0
with open("notes.txt", encoding="utf-8") as f:
for line in f:
if line.strip():
count += 1
print(count, f.closed)
実行前に、出力される1行を正確に書き出し、2つの値がそれぞれなぜそうなるかを説明する。notes.txt が改行で終わっていなかったら結果は変わるか?
実行前に予測する。パスで迷ったら先に Path.cwd() を表示する。反復回数と空でない行数を比較し、空行判定は生の行ではなく strip() で決める。
count = 0
with open("notes.txt", encoding="utf-8") as f:
for line in f:
if line.strip():
count += 1
print(count, f.closed)
出力:3 True。追跡:ループは 'alpha\n'、'beta\n'、'gamma\n'(最終行に改行が無ければ 'gamma')を順に受け取る。strip() 後もどれも空ではないので count は3になり、最終行の末尾の改行は4行目を作らない。print は with ブロックを抜けた後に実行されるので、f はすでに閉じており f.closed は True。
予測が観察した出力と一致し、相対パスが Path.cwd() 基準で解決されると述べ、with ブロック終了後のファイルオブジェクトの closed 状態(f.closed)を示せる。
Authoritative Source Resources & Provenance
Automate the Boring Stuff with Python, 3rd edition
該当セクション・タイムスタンプ: Chapter 10; Practice Questions; Appendix B answers
検証バージョンと日付: Public edition checked 2026-11-01; moving pages may change
Beginner teaching and answer-keyed practice before checking exact semantics in the Python reference; selected chapters only, not the book's entire automation stack.
No prior programming required for Chapter 1; later chapters assume its basic Python concepts.
Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.
比較対象候補リソースと選定評価 (2)
Guided Python syntax but assumes programming familiarity; paired with the beginner text rather than used as its replacement.
Lectures and problem sets teach a broader CS1 course; the book offers shorter text-first entry and an answer appendix.
The Python Tutorial: Input and Output
該当セクション・タイムスタンプ: Section 7.2 (Reading and Writing Files)
検証バージョンと日付: Python 3.12 documentation; verified 2026-10-30
Primary reference for open(), explicit encodings, and the with statement as guaranteed cleanup.
The lesson explains all required behavior locally and can be completed offline; help(open) also works in the interpreter.
比較対象候補リソースと選定評価 (2)
Friendly walkthrough, but it is a secondary tutorial with mixed access tiers rather than the normative language reference.
Stream-layer reference for advanced cases; the tutorial chapter covers the open()/with patterns the drills require.