路徑、編碼與安全的檔案讀取
只有在記錄了預測和觀察到的證據之後,才允許使用協助。
Prerequisites
完成上一個活動;如遇卡關,請使用列出的恢復連結。
Learning Objective
在 with 區塊內用明確的 UTF-8 編碼讀取文字檔並統計非空行數。執行前先預測結果,再解釋為什麼相對路徑取決於目前工作目錄。
Instructions
學習來源:在本活動現有的閱讀與練習時段內,參考 Automate the Boring Stuff with Python, 3rd edition 的 Chapter 10; Practice Questions; Appendix B answers,用自己的話解釋一處與本地任務的聯繫。保留現有練習與驗收檢查;若外部資料無法存取,使用課程自寫的解釋。在全新目錄中建立 notes.txt,恰好三行:alpha、beta、gamma。open("notes.txt") 這類相對路徑會相對 Path.cwd() 解析,而不是相對腳本所在資料夾。迭代檔案物件每次產生一行,每行都保留結尾的 "\n",但最後一行可能例外:如果檔案不以換行符號結尾,最後一行就沒有換行符號(寫成 "alpha\nbeta\ngamma" 的檔案,最後一行是 'gamma')。line.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)
執行前先寫下它會印出的那一行,並解釋兩個值各自為什麼是這樣。如果 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,最後一行結尾的換行符號不會產生第四行。print 在 with 區塊結束之後才執行,此時 f 已關閉,所以 f.closed 為 True。
預測與觀察到的輸出一致;能說明相對路徑相對 Path.cwd() 解析;能展示 with 區塊結束後檔案物件的關閉狀態(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.