使用名为 mode_demo.txt 的新文件,不要使用输入文件。先写入 A 和换行符,再追加 B 和换行符。文件包含 A 和 B 两行。运行一个新的 w 代码块写入 C,会用 C 替换原来的两行。文件写入使用字符串。
with open("mode_demo.txt", "w", encoding="utf-8") as target:
target.write("A\n")
with open("mode_demo.txt", "a", encoding="utf-8") as target:
target.write("B\n")
先预测,再揭晓
向新的 demo.txt 写入 "red\n",再追加 "blue\n"。文件文本是什么?之后一个 w 代码块写入 "green\n"。还剩下什么?
展开解题思路
追加后:"red\nblue\n",共两行。用 w 打开会清空原内容;之后写入后,只剩下 "green\n"。
# Use a report filename distinct from the input log.
from pathlib import Path
report = Path("practice_report.txt")
report.write_text("count: 3\n", encoding="utf-8")
print(report.read_text(encoding="utf-8"))
# A mean is the sum divided by the count; dividing by zero is invalid.
readings = [24, 27, 29]
if readings:
print("count", len(readings))
print("mean", sum(readings) / len(readings))
else:
print("no valid readings")