【Python 高频 API 速学 ⑥】
一、为什么叫「2 保险」?
• 第一重:with open → 自动关门,永不漏文件句柄。
• 第二重:pathlib → Windows、macOS、Linux 路径写法统一,API 面向对象。
两者加起来,90 % 的文件操作不用再写 try-finally 或手动拼斜杠。
二、两保险一览
保险 | 核心语法 | 默认模式 | 额外杀器 |
---|---|---|---|
with open() | 上下文管理器 | ‘r’ 文本读 | encoding, newline, buffering |
pathlib.Path | 面向对象路径 | — | / 运算符拼路径,glob, read_text, write_text |
三、一行代码场景秀
- 一次性读整个文件(小文件)
from pathlib import Path
content = Path('poem.txt').read_text(encoding='utf-8')
- 一次性写文件并自动创建目录
out = Path('output/report.csv')
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text('name,score\n')
- 大文件流式处理
from pathlib import Path
with Path('big.log').open() as f:for line in f:if 'ERROR' in line:print(line.rstrip())
- 批量改后缀
for p in Path('photos').glob('*.jpeg'):p.rename(p.with_suffix('.jpg'))
- 拼接跨平台路径
root = Path.home() / 'Documents' / 'project'
config = root / 'config.yaml'
- 统计代码行数(含子目录)
print(sum(1for p in Path('src').rglob('*.py')for _ in p.open(encoding='utf-8')))
四、mini 实战:5 行生成「当日备份」脚本
需求:把 ./data 文件夹打包成 zip,文件名带时间戳。
from pathlib import Path
from datetime import datetime
import zipfiletoday = datetime.now().strftime('%Y%m%d')
backup = Path(f'backup_{today}.zip')
with zipfile.ZipFile(backup, 'w') as zf:for file in Path('data').rglob('*'):zf.write(file, arcname=file.relative_to('data'))
print('Backup →', backup.resolve())
核心动作:
• Path.rglob('*')
递归遍历
• with zipfile...
自动关闭文件句柄
• resolve()
给出绝对路径,方便日志记录
五、记忆口令
“open 配 with,文件永不漏; 斜杠用 /,Path 跨平台。”