第10章 · 文件和异常
学习读写文件、异常处理,并使用json模块持久化存储数据。
知识点讲解
读取与写入文件
使用 open() 打开文件,配合 with 语句可在使用完毕后自动关闭文件。读取方式有 read()(全文)、readlines()(逐行)、for line in file(逐行迭代)。写入使用 "w"(覆盖)、"a"(追加)模式。注意文件路径和编码(通常 encoding="utf-8")。
异常处理
异常让程序在出错时不会崩溃而是给出友好提示。使用 try-except 捕获异常:
try:
print(5/0)
except ZeroDivisionError:
print("不能除以零!")
else:
print("计算成功")
except 捕获异常,else 在try成功时执行,finally 无论如何都执行。处理异常时不要静默吞掉错误,应给出有意义的提示。
json存储数据
json模块让数据以JSON格式持久化。写入用 json.dump(数据, 文件对象),读取用 json.load(文件对象)。典型的应用是记住用户偏好:程序启动时读取、关闭时保存,实现"记住上次状态"的功能。
代码示例
文件读写
演示读取与写入文件。
# 读取
with open("pi_digits.txt") as file:
contents = file.read()
print(contents)
# 逐行读取
with open("pi_digits.txt") as file:
for line in file:
print(line.rstrip())
# 写入(覆盖)/ 追加
with open("programming.txt", "w") as file:
file.write("我喜欢编程。\n")
with open("programming.txt", "a") as file:
file.write("我每天写一点代码。\n")
异常与json
演示try-except与json存储。
import json
try:
print(5 / 0)
except ZeroDivisionError:
print("不能除以零!")
else:
print("计算成功")
# json 存储
numbers = [1, 2, 3, 4, 5]
with open("numbers.json", "w") as f:
json.dump(numbers, f)
with open("numbers.json") as f:
loaded = json.load(f)
print(loaded)