pathlib
面向对象的文件系统路径。对于底层的路径字符串操作,你也可以使用 os.path 模块。pathlib 在 Python 3.4 引入,提供跨平台的路径表示与操作。
路径类型概览
路径类分为两类:
- 纯路径(Pure Paths):只做路径计算,不访问文件系统。如
PurePath、PurePosixPath、PureWindowsPath。适合在 Unix 上处理 Windows 路径、或只做字符串式路径拼接与解析。 - 具体路径(Concrete Paths):在纯路径基础上提供 I/O 操作。如
Path、PosixPath、WindowsPath。
不确定用哪个时,用 Path 即可:在运行平台上会自动实例化为 PosixPath 或 WindowsPath。
Path
Path 是推荐使用的类,同时具备路径运算和文件系统访问能力。
基础用法
路径用 / 拼接;可查询存在性、是否目录/文件,并用 open() 或 read_text/write_text 读写。
from pathlib import Path
# 当前目录、拼接路径
p = Path('.')
q = p / 'docs' / 'readme.txt'
# 列出当前目录下的子目录
dirs = [x for x in p.iterdir() if x.is_dir()]
# 列出所有 .py 文件(含子目录)
py_files = list(p.glob('**/*.py'))
# 查询
q.exists()
q.is_dir()
q.is_file()
# 读文本
text = q.read_text(encoding='utf-8')
# 写文本(会覆盖)
q.write_text('hello', encoding='utf-8')
# 或按需 open
with q.open(encoding='utf-8') as f:
line = f.readline()
常用属性
| 属性 | 说明 |
|---|---|
name | 路径最后一段(文件名或目录名),含后缀 |
stem | 最后一段去掉后缀的部分 |
suffix | 最后一段的后缀(如 .txt) |
parent | 父目录路径 |
parents | 各级父目录的可切片序列 |
parts | 路径各部分的元组 |
anchor | 根(如 Windows 的 C:\ 或 Unix 的 /) |
drive | 盘符(Windows,如 C:) |
from pathlib import Path
p = Path('/usr/share/data/config.json')
p.name # 'config.json'
p.stem # 'config'
p.suffix # '.json'
p.parent # Path('/usr/share/data')
p.parts # ('/', 'usr', 'share', 'data', 'config.json')
常用方法
查询与判断
- exists():路径是否存在
- is_dir():是否为目录
- is_file():是否为文件(且存在)
- resolve():转为绝对路径并解析符号链接,推荐用其取"规范绝对路径"
- absolute():转为绝对路径(不解析符号链接)
遍历与匹配
- iterdir():当前目录下的条目(不递归),每个元素是
Path - glob(pattern):当前目录下按 pattern 匹配(如
*.py),不递归 - rglob(pattern):递归匹配,等价于
glob('**/' + pattern)
from pathlib import Path
p = Path('.')
# 仅当前目录
for item in p.iterdir():
print(item)
# 当前目录下 .py
for f in p.glob('*.py'):
print(f)
# 所有子目录中的 .py
for f in p.rglob('*.py'):
print(f)
# 绝对路径
abs_p = p.resolve()
目录与文件操作
- mkdir(parents=False, exist_ok=False):创建目录;
parents=True可创建多级,exist_ok=True时已存在不报错 - read_text(encoding=None, errors=None):以文本方式读取整个文件
- write_text(data, encoding=None, errors=None):以文本方式写入(覆盖)
- open(mode='r', ...):与内置
open()一致,可指定'a'追加等
from pathlib import Path
# 创建多级目录
Path('output/logs').mkdir(parents=True, exist_ok=True)
# 读写文本
path = Path('output/hello.txt')
path.write_text('你好', encoding='utf-8')
print(path.read_text(encoding='utf-8'))
# 追加写入用 open
with path.open('a', encoding='utf-8') as f:
f.write('\n追加一行')
PurePath
当只需要做路径拼接、分解、归一化,而不访问磁盘时,可用 PurePath(及 PurePosixPath / PureWindowsPath)。例如在 Linux 上处理 Windows 路径字符串:
from pathlib import PureWindowsPath, PurePosixPath
# 在任意平台上解析 Windows 路径
win = PureWindowsPath('C:/Program Files/App/config.ini')
print(win.name) # 'config.ini'
print(win.parent) # PureWindowsPath('C:/Program Files/App')
# 纯路径没有 exists()、read_text() 等 I/O 方法
Path 继承自 PurePath,因此上述属性(name、stem、parent 等)和纯路径上的方法在 Path 上同样可用。