文件操作与序列化
本节定位
这一节让程序的数据可以保存下来、再读回来。文件读写、CSV、JSON 和序列化是数据集处理、训练日志、配置文件、模型结果保存的基础,也是从内存中的临时代码走向真实项目的关键一步。
学习目标
- 掌握文件的读写操作(
open、read、write) - 理解
with语句的作用和好处 - 学会处理 CSV、JSON 等常用数据格式
- 理解序列化和反序列化的概念
为什么需要文件操作?
到目前为止,你的程序中的数据都在内存中——程序一关,数据就没了。但在真实场景中:
- 训练好的 AI 模型需要保存到文件,下次直接加载
- 数据集存在 CSV 文件里,需要读取到程序中
- 训练日志需要写入文件,方便后续分析
- 配置参数存在 JSON 文件里,启动时需要加载
文件操作就是让你的程序能持久化保存数据。
文件读写基础
打开文件:open()
# 基本语法
file = open("文件路径", "模式", encoding="编码")
常用模式:
| 模式 | 含义 | 文件不存在时 |
|---|---|---|
"r" | 读取(默认) | 报错 |
"w" | 写入(覆盖) | 自动创建 |
"a" | 追加(在末尾添加) | 自动创建 |
"x" | 创建(文件已存在则报错) | 自动创建 |
"rb" | 读取二进制文件 | 报错 |
"wb" | 写入二进制文件 | 自 动创建 |
写入文件
# 方式 1:手动打开和关闭(不推荐)
file = open("hello.txt", "w", encoding="utf-8")
file.write("你好,世界!\n")
file.write("我正在学习 Python 文件操作。\n")
file.close() # 别忘了关闭文件!
# 方式 2:使用 with 语句(推荐!)
with open("hello.txt", "w", encoding="utf-8") as file:
file.write("你好,世界!\n")
file.write("我正在学习 Python 文件操作。\n")
# 离开 with 块时,文件自动关闭,不需要手动 close()
为什么推荐 with 语句?
with 语句有两个好处:
- 自动关闭文件——不用担心忘记
close() - 异常安全——即使代码出错,文件也会被正确关闭
以后写文件操作,永远用 with。
读取文件
# 读取全部内容
with open("hello.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
# 逐行读取
with open("hello.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip()) # strip() 去掉行尾的换行符
# 读取所有行到列表
with open("hello.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
print(lines) # ['你好,世界!\n', '我正在学习 Python 文件操作。\n']
追加内容
# "a" 模式:在文件末尾追加,不会覆盖原有内容
with open("log.txt", "a", encoding="utf-8") as file:
file.write("2026-02-09: 开始学习\n")
file.write("2026-02-09: 完成第一章\n")
写入多行
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open("output.txt", "w", encoding="utf-8") as file:
file.writelines(lines) # 写入一个字符串列表
# 或者用 print 写入文件
with open("output.txt", "w", encoding="utf-8") as file:
print("第一行", file=file) # print 可以指定输出到文件
print("第二行", file=file)
print("第三行", file=file)
实际案例:处理不同文件格式
CSV 文件
CSV(Comma-Separated Values)是最常见的数据文件格式:
import csv
# 写入 CSV
students = [
["姓名", "年龄", "成绩"],
["张三", 20, 85],
["李四", 21, 92],
["王五", 19, 78],
]
with open("students.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(students)
# 读取 CSV
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
header = next(reader) # 读取表头
print(f"列名: {header}")
for row in reader:
name, age, score = row
print(f"{name}, {age}岁, 成绩: {score}")
# 用字典方式读取(更方便)
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['姓名']} 的成绩是 {row['成绩']}")
JSON 文件
JSON 是 Web 开发和 API 中最常用的数据格式:
import json
# 写入 JSON
config = {
"model": "ResNet-50",
"learning_rate": 0.001,
"epochs": 100,
"batch_size": 32,
"classes": ["猫", "狗", "鸟"],
"use_gpu": True
}
with open("config.json", "w", encoding="utf-8") as file:
json.dump(config, file, ensure_ascii=False, indent=2)
# 读取 JSON
with open("config.json", "r", encoding="utf-8") as file:
loaded_config = json.load(file)
print(f"模型: {loaded_config['model']}")
print(f"学习率: {loaded_config['learning_rate']}")
print(f"类别: {loaded_config['classes']}")
生成的 config.json 文件内容:
{
"model": "ResNet-50",
"learning_rate": 0.001,
"epochs": 100,
"batch_size": 32,
"classes": ["猫", "狗", "鸟"],
"use_gpu": true
}
ensure_ascii=False
默认情况下,json.dump() 会把中文转成 Unicode 编码(如 \u732b)。加上 ensure_ascii=False 可以保留中文字符,让文件更可读。