小脚本里经常要拼路径、建目录、写个文件。直接用字符串加 / 很容易在不同系统上别扭,标准库的 pathlib 会舒服一点。
环境:Python 3.8+。保存成 pathlib-demo.py:
from pathlib import Path
root = Path('demo-output')
root.mkdir(exist_ok=True)
file = root / 'note.txt'
file.write_text('hello pathlib\n', encoding='utf-8')
print(file.resolve())
print(file.read_text(encoding='utf-8').strip())
print(file.suffix)
跑一下:
python pathlib-demo.py
root / 'note.txt' 这种写法比手动拼字符串清楚些,mkdir、read_text、write_text 也能少写几行样板代码。
如果项目里路径逻辑已经很多了,早点统一成 Path 对象会省不少来回转换的小麻烦。