pathlib.Path 提供面向对象的文件路径操作,替代 os.path,支持链式调用和路径拼接。

路径属性

属性说明示例
name文件名(含扩展名)Path('a/b.txt').name'b.txt'
stem文件名(不含扩展名)Path('a/b.txt').stem'b'
suffix扩展名Path('a/b.txt').suffix'.txt'
suffixes多个扩展名列表Path('a.tar.gz').suffixes['.tar', '.gz']
parent父目录Path('a/b/c').parentPath('a/b')
parents[n]第 n 级父目录Path('a/b/c').parents[1]Path('a')

路径检查

path = Path('/home/user/file.txt')
 
path.exists()       # 路径是否存在
path.is_file()      # 是否为文件
path.is_dir()       # 是否为目录
path.is_symlink()   # 是否为符号链接

路径操作

path = Path('/home/user/docs/example.txt')
 
# 创建目录
Path('new/dir').mkdir(parents=True, exist_ok=True)
 
# 创建空文件
path.touch(exist_ok=True)
 
# 重命名
path.rename('new_name.txt')
 
# 删除文件
path.unlink()
 
# 删除空目录
Path('empty_dir').rmdir()
 
# 获取绝对路径
path.resolve()
 
# 替换文件名/扩展名
path.with_name('other.txt')
path.with_suffix('.md')
 
# 相对路径
path.relative_to('/home/user')  # Path('docs/example.txt')

文件读写

# 读取文件
content = Path('file.txt').read_text(encoding='utf-8')
data = Path('file.bin').read_bytes()
 
# 写入文件
Path('file.txt').write_text('content', encoding='utf-8')
Path('file.bin').write_bytes(b'data')
 
# 打开文件
with path.open('r') as f:
    content = f.read()

目录遍历

dir_path = Path('/home/user/docs')
 
# 遍历当前目录
for child in dir_path.iterdir():
    print(child)
 
# glob 匹配
for txt in dir_path.glob('*.txt'):
    print(txt)
 
# 递归 glob
for txt in dir_path.rglob('*.txt'):
    print(txt)

路径拼接

# 使用 / 操作符
path = Path('/home') / 'user' / 'docs' / 'file.txt'
 
# 拼接多个部分
Path('/home').joinpath('user', 'docs', 'file.txt')

示例

from pathlib import Path
 
path = Path("/home/user/docs/example.txt")
 
print(path.name)      # 'example.txt'
print(path.stem)      # 'example'
print(path.suffix)    # '.txt'
print(path.parent)    # '/home/user/docs'
 
if path.exists():
    print(f"{path} 存在")