Add Day_13: 文件读写与JSON

This commit is contained in:
2026-08-22 01:09:38 +08:00
parent f662556cc1
commit 03eddc109a
+89
View File
@@ -0,0 +1,89 @@
# Day_13 · 文件读写与 JSON:让数据活到下次运行
> 预计耗时:25~30 分钟
> 程序一关,变量就没了。想让数据存下来(这就是"持久化",数据库干的事),先从文件开始。
> Django 的数据库、缓存的本质,都是"把数据存起来再读回来"。
## 今日知识点
- 写文件:`with open("note.txt", "w") as f: f.write(内容)`(`w` = 覆盖写)
- 读文件:`with open("note.txt", "r") as f: 内容 = f.read()`
- `with` 会自动关文件,不用手动 close
- **JSON**:一种"把字典/列表变成文本"的格式,`json.dumps` 变文本、`json.loads` 变回数据
- 为什么重要:HTTP 接口传输的数据、配置文件,全是 JSON 格式
## 先学(教程)
- 菜鸟教程("文件方法"一节,看 open/read/write 即可):https://www.runoob.com/python3/python3-file-methods.html
- 菜鸟教程("JSON"一节):https://www.runoob.com/python3/python3-json.html
- B站黑马教程(看讲"文件操作"的几集):https://www.bilibili.com/video/BV1qW4y1a7fU/
## 任务(后做)
新建 `day13.py`:
1. 写入再读回:
```python
text = input("写一句话存起来:")
with open("note.txt", "w", encoding="utf-8") as f:
f.write(text)
with open("note.txt", "r", encoding="utf-8") as f:
content = f.read()
print("读回来的是:", content)
```
运行后确认同目录出现了 `note.txt`,且内容一致。(注意 `encoding="utf-8"`,否则中文会乱码。)
2. 用 JSON 存字典:
```python
import json
user = {"name": "张三", "age": 18, "city": "青岛"}
with open("user.json", "w", encoding="utf-8") as f:
json.dump(user, f, ensure_ascii=False) # ensure_ascii=False 让中文可读
with open("user.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["name"], loaded["age"]) # 从文件里还原的字典
```
3. **进阶(加分)**:把 Day_5 的"三个用户列表"用 `json.dump` 存进 `users.json`,
再读回来遍历打印每个人的名字。
## 完成标准
- [ ] note.txt 和 user.json 出现在同目录,读回内容一致
- [ ] 能说出 `json.dump` 和 `json.load` 各是干嘛的
- [ ] (进阶)用户列表存取成功
**提交方式**:把 `day13.py` 代码贴在当日工单评论里。
## 参考解答(先做再看)
```python
text = input("写一句话存起来:")
with open("note.txt", "w", encoding="utf-8") as f:
f.write(text)
with open("note.txt", "r", encoding="utf-8") as f:
print("读回来的是:", f.read())
import json
user = {"name": "张三", "age": 18, "city": "青岛"}
with open("user.json", "w", encoding="utf-8") as f:
json.dump(user, f, ensure_ascii=False)
with open("user.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["name"], loaded["age"])
# 进阶
users = [
{"name": "张三", "age": 19},
{"name": "李四", "age": 20},
{"name": "王五", "age": 18},
]
with open("users.json", "w", encoding="utf-8") as f:
json.dump(users, f, ensure_ascii=False)
with open("users.json", "r", encoding="utf-8") as f:
for u in json.load(f):
print(u["name"])
```