Python pathlib 实用指南:告别 os.path 的 5 个技巧
【摘要】 处理文件路径时,很多人仍习惯 os.path.join 拼字符串。自 Python 3.4 起,标准库的 pathlib 把路径做成对象,代码更短、更不容易出错,而且跨 Windows / Linux 通用。下面是 5 个日常最有用的技巧,示例均可直接运行。 1. 用 / 运算符拼接路径from pathlib import Pathp = Path("a") / "b" / "c.txt"...
处理文件路径时,很多人仍习惯 os.path.join 拼字符串。自 Python 3.4 起,标准库的 pathlib 把路径做成对象,代码更短、更不容易出错,而且跨 Windows / Linux 通用。下面是 5 个日常最有用的技巧,示例均可直接运行。
1. 用 / 运算符拼接路径
from pathlib import Path
p = Path("a") / "b" / "c.txt"
print(p) # a/b/c.txt(Windows 上是 a\b\c.txt)
print(p.name) # c.txt
print(p.stem) # c
print(p.suffix) # .txt
print(p.parent) # a/b
不用再担心分隔符,也不用手写字符串切割来取文件名和后缀。
2. 读写文本一行搞定
from pathlib import Path
import tempfile
d = Path(tempfile.mkdtemp())
f = d / "demo" / "hello.txt"
f.parent.mkdir(parents=True, exist_ok=True) # 递归创建目录,已存在不报错
f.write_text("你好\n第二行", encoding="utf-8")
print(f.read_text(encoding="utf-8").splitlines()) # ['你好', '第二行']
write_text / read_text 内部已处理打开与关闭文件。小文件很方便;大文件仍建议用 with f.open() 逐行读取。务必显式指定 encoding,避免在不同系统上默认编码不同。
3. 用 glob / rglob 查找文件
print(sorted(x.name for x in d.rglob("*.txt"))) # ['hello.txt']
glob("*.py") 只匹配当前目录,rglob("*.py") 会递归子目录。返回的是生成器,处理大目录时不会一次占满内存。
4. 修改后缀与文件名
f = Path("report/data.csv")
print(f.with_suffix(".json")) # report/data.json
print(f.with_name("other.csv")) # report/other.csv
print(f.with_stem("new")) # report/new.csv(Python 3.9+)
这些方法返回新的路径对象,不会改动磁盘上的文件,需要重命名时再调用 f.rename(新路径)。
5. 计算相对路径与安全写入
print((d / "demo" / "hello.txt").relative_to(d)) # demo/hello.txt
写配置文件时,可以先写临时文件再原子替换,避免中途出错留下半个文件:
import os
target = d / "demo" / "hello.txt"
tmp = target.with_name(target.name + ".tmp")
tmp.write_text("new", encoding="utf-8")
os.replace(tmp, target) # 同一文件系统内是原子操作
print(target.read_text()) # new
pathlib 对象可直接传给 open()、shutil、os.replace 等函数,与旧代码兼容。
常见坑
Path.relative_to在路径不在基准目录下时会抛ValueError,需要先判断或捕获。Path.home()、Path.cwd()分别取用户目录与当前工作目录,比拼环境变量更稳妥。- 需要字符串时用
str(p)或os.fspath(p)。 - 删除文件用
p.unlink(missing_ok=True)(3.8+),目录用shutil.rmtree。
小结
新项目里优先使用 pathlib:拼接用 /,读写用 read_text/write_text,查找用 rglob,改后缀用 with_suffix。代码更短,也更容易跨平台。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)