写小脚本时如果一直 open() 加字符串路径,目录一多就有点乱。标准库里的 pathlib.Path 可以把路径和读写放在一起,看着会清爽些。
环境:Python 3.8+。可以建个文件 path-demo.py:
from pathlib import Path
base = Path('demo-data')
base.mkdir(exist_ok=True)
file = base / 'hello.txt'
file.write_text('hello\n', encoding='utf-8')
text = file.read_text(encoding='utf-8')
print(text.strip())
print(file.resolve())
跑一下:
python path-demo.py
输出里会有 hello,然后打印出这个文件的绝对路径。
我觉得它适合那种本地处理配置、生成临时文本的小脚本。不是说 open() 不好,只是路径拼接、建目录、读写文本都放到 Path 上之后,少写一点胶水代码。