4.1 文件读写基础
文件操作
🎯 小白理解:什么是
with open()语句?想象你去图书馆借书:
- 进门 → 打开文件(
open())- 借书/还书 → 读取/写入内容
- 出门 → 关闭文件(自动完成!)
with语句就是一个"自动关门"的保镖:with open(...) as f: # 开门,给你一个文件对象 f # 在这里做事情 # 离开 with 块后,门自动关上为什么要用
with?
- 不用 with:你要手动调用
f.close(),忘了就会"资源泄露"(就像借了书不还)- 用 with:自动帮你关,就算代码出错也会关(Python 的"好习惯")
参数解释:
参数 含义 类比 "config.txt"文件名/路径 书名 "w"写入模式(write) 拿空白本子写字 "r"读取模式(read) 看书 "a"追加模式(append) 在本子后面继续写 encoding="utf-8"编码格式 用什么语言写(中文必须用 utf-8!) ⚠️ 重要提醒:
"w"模式会清空原文件内容!想保留原内容,用"a"(追加)。
python
# 写入文件
with open("config.txt", "w", encoding="utf-8") as f:
f.write("model=gpt-4\n")
f.write("temperature=0.7\n")
# 读取文件
with open("config.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读取
with open("config.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())pathlib 路径管理
🎯 小白理解:什么是 pathlib?为什么要用它?
传统方式处理路径(麻烦且容易出错):
python# 拼接路径要用 os.path.join import os path = os.path.join("configs", "agent.json") # 繁琐!pathlib 方式(现代、优雅):
pythonfrom pathlib import Path path = Path("configs") / "agent.json" # 简洁!像写地址一样为什么用
/拼接路径?Python 允许自定义运算符行为。
Path对象重新定义了/的含义:
- 普通数字:
10 / 2= 5(除法)- Path 对象:
Path("a") / "b"=Path("a/b")(路径拼接)pathlib 的好处:
操作 传统方式 pathlib 方式 拼接路径 os.path.join(a, b)a / b读取文件 open(path).read()path.read_text()创建目录 os.makedirs(path)path.mkdir()检查存在 os.path.exists(path)path.exists()类比:
pathlib就像一个智能导航,不管你在 Windows(\)还是 Mac/Linux(/),它都能自动处理路径分隔符!
python
from pathlib import Path
# 创建路径对象
config_dir = Path("configs")
config_file = config_dir / "agent.json"
# 创建目录
config_dir.mkdir(parents=True, exist_ok=True)
# 写入文件
config_file.write_text('{"model": "gpt-4"}', encoding="utf-8")
# 读取文件
content = config_file.read_text(encoding="utf-8")
print(content)
# 检查存在
if config_file.exists():
print(f"文件大小: {config_file.stat().st_size} 字节")下一节:4.2 JSON 与 YAML