Python:本地脚本读写文件,`pathlib.Path` 比手拼路径顺一点

56 次浏览3 条回复

写小脚本时如果一直 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 上之后,少写一点胶水代码。

Path 还有个小细节挺顺手:脚本里要定位当前文件旁边的资源时,可以用 Path(__file__).parent,比依赖运行时的当前目录稳一点。

from pathlib import Path

config = Path(__file__).parent / 'config.json'
print(config.read_text(encoding='utf-8'))

尤其是脚本从别的目录被调用时,这个差别还挺明显。

还有个我觉得很省心的是先用 exists()is_file() 判断一下,报错会少一点:

from pathlib import Path

p = Path('demo-data/hello.txt')
if p.is_file():
    print(p.read_text(encoding='utf-8'))
else:
    print('file not found:', p)

小脚本里处理可选配置、缓存文件之类的场景挺常见。比一上来就拼字符串再 open() 猜路径,排查时舒服些。

Path 配合 glob() 找文件也挺自然,处理一批本地文本时少写不少拼接:

from pathlib import Path

for p in Path('demo-data').glob('*.txt'):
    print(p.name, p.read_text(encoding='utf-8').strip())

如果要递归子目录,可以换成 rglob('*.txt')。这种小脚本里比手写 os.walk 轻一点。