Skip to main content

文件与异常

程序运行时的数据都是临时的,程序关闭就没了。要把数据持久化保存,就需要读写文件。Python 提供了简洁的文件操作 API。

读取文件

读取整个文件

open() 打开文件,with 语句会自动关闭文件:

with open("data.txt") as f:
content = f.read()
print(content)

read() 返回文件的全部内容。注意文件末尾可能有个换行符,可以用 rstrip() 去掉:

with open("data.txt") as f:
content = f.read().rstrip()
print(content)

逐行读取

大文件不适合一次性读进内存,可以逐行处理:

with open("data.txt") as f:
for line in f:
print(line.rstrip())

读取为列表

with open("data.txt") as f:
lines = f.readlines()

for line in lines:
print(line.rstrip())

文件路径

  • 相对路径:从当前工作目录算起,如 "data/members.txt"
  • 绝对路径:完整路径,如 /Users/alice/project/data.txt(macOS/Linux)或 C:/Users/alice/project/data.txt(Windows)

Windows 路径里的反斜杠在 Python 字符串里是转义符,可以用原始字符串:

path = r"C:/Users/alice/project/data.txt"

或者用正斜杠(Python 会自动处理):

path = "C:/Users/alice/project/data.txt"

写入文件

打开文件时指定模式:

  • "r":读取(默认)
  • "w":写入,会覆盖原有内容
  • "a":追加,在文件末尾添加
  • "r+":读写
# 写入(覆盖)
with open("output.txt", "w") as f:
f.write("第一行\n")
f.write("第二行\n")

# 追加
with open("output.txt", "a") as f:
f.write("第三行\n")

注意: "w" 模式会清空原有内容,用之前确认不需要保留旧数据。

异常处理

程序运行中可能遇到各种错误,比如文件不存在、权限不足等。用 try-except 捕获异常,让程序优雅地处理错误:

try:
with open("不存在的文件.txt") as f:
content = f.read()
except FileNotFoundError:
print("文件不存在")

常见异常类型

异常说明
FileNotFoundError文件或目录不存在
PermissionError权限不足
ZeroDivisionError除以零
ValueError值类型错误
TypeError类型不匹配

else 和 finally

else 块在没有异常时执行,finally 块无论有无异常都执行:

try:
result = 10 / num
except ZeroDivisionError:
print("不能除以零")
else:
print(f"结果是 {result}")
finally:
print("计算结束")

静默处理

有时候不想做任何处理,只是跳过错误:

try:
with open("optional.txt") as f:
content = f.read()
except FileNotFoundError:
pass # 什么都不做,继续执行

JSON 数据

JSON 是网络传输和配置文件最常用的数据格式。Python 用 json 模块处理:

import json

# 写入 JSON
data = {
"name": "Alice",
"skills": ["Python", "Rust"],
"score": 92.5,
}

with open("data.json", "w") as f:
json.dump(data, f, indent=2)

生成的 data.json

{
"name": "Alice",
"skills": ["Python", "Rust"],
"score": 92.5
}

读取 JSON:

with open("data.json") as f:
data = json.load(f)

print(data["name"]) # Alice
print(data["skills"]) # ['Python', 'Rust']

json.dump()json.load() 分别用于文件对象,json.dumps()json.loads() 用于字符串。