首页 › Python 标准库 › pathlib 文件路径
pathlib 文件路径
pathlib 用面向对象的方式处理文件路径,比字符串拼接和 os.path 更直观,并且自动处理不同系统的路径分隔符。
from pathlib import Path
p = Path("docs") / "notes" / "python.md"
print(p.name) # python.md
print(p.stem) # python
print(p.suffix) # .md
print(p.parent) # docs/notes
读写文件
p = Path("hello.txt")
p.write_text("你好,pathlib", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
遍历目录
for f in Path(".").glob("*.py"):
print(f, f.stat().st_size)
# 递归查找所有图片
images = list(Path("photos").rglob("*.jpg"))
常用操作
d = Path("output/2026")
d.mkdir(parents=True, exist_ok=True) # 创建多级目录
print(d.exists(), d.is_dir())
Path("old.txt").rename("new.txt")
实战:按扩展名整理下载目录
from pathlib import Path
downloads = Path.home() / "Downloads"
for f in downloads.iterdir():
if f.is_file() and f.suffix:
target = downloads / f.suffix.lstrip(".").lower()
target.mkdir(exist_ok=True)
f.rename(target / f.name)练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 统计当前目录下(包括子目录)所有 .py 文件的数量和总行数。
查看参考答案
from pathlib import Path
files = list(Path(".").rglob("*.py"))
lines = sum(len(p.read_text(encoding="utf-8", errors="ignore").splitlines()) for p in files)
print(len(files), "个文件,共", lines, "行")练习 2 给定路径字符串 "/data/2026/report.final.csv",取出父目录、文件名、主名和扩展名。
查看参考答案
from pathlib import PurePosixPath
p = PurePosixPath("/data/2026/report.final.csv")
print(p.parent, p.name, p.stem, p.suffix)参考输出:
/data/2026 report.final.csv report.final .csv