Python:临时处理路径,`pathlib` 比字符串拼接稳一点

24 次浏览4 条回复

小脚本里经常要拼路径、建目录、写个文件。直接用字符串加 / 很容易在不同系统上别扭,标准库的 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' 这种写法比手动拼字符串清楚些,mkdirread_textwrite_text 也能少写几行样板代码。

如果项目里路径逻辑已经很多了,早点统一成 Path 对象会省不少来回转换的小麻烦。

还有个小细节挺实用:函数入参如果可能是字符串也可能是 Path,可以一进来就 p = Path(p) 统一掉。后面全程用 /exists()with_suffix() 这类方法,代码会干净很多。

不过传给某些老库时还是要留意一下,它们可能只认字符串,这时候再 str(p) 就行。

pathlib 还有一个我觉得容易被忽略的是 Path.cwd()Path.home(),写配置文件路径时比手写 ~ 或当前目录字符串稳一点。

比如临时放到用户目录下可以这样:

from pathlib import Path

config = Path.home() / '.demo-app' / 'config.toml'
config.parent.mkdir(parents=True, exist_ok=True)
config.write_text('debug = true\n', encoding='utf-8')
print(config)

parents=True 也挺关键,不然中间目录不存在会直接报错。

补一个我常会顺手用的:找文件时 Path.glob() / rglob() 比自己递归目录轻松一点。

from pathlib import Path

for p in Path('demo-output').rglob('*.txt'):
    print(p.name, p.stat().st_size)

小目录挺方便,但目录很大时别直接无脑 list(...),边迭代边处理会稳些。

还有 relative_to() 也挺适合做输出路径展示。比如扫描到一堆文件时,不想把绝对路径全打出来:

from pathlib import Path

root = Path('demo-output')
for p in root.rglob('*.txt'):
    print(p.relative_to(root))

这样输出就是相对 demo-output 的路径,日志里会清爽一点。前提是这个文件确实在 root 下面,不然会抛 ValueError