路径、编码与安全的文件读取
只有在记录了预测和观察到的证据之后,才允许使用协助。
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.