Pathlib 是 Python 3.4+ 引入的面向对象的文件系统路径处理模块,提供了更直观、更Pythonic的方式来处理文件和目录路径。
1. 核心类介绍
Path 类
from pathlib import Path
# 创建Path对象
p = Path('/home/user/documents') # Linux/Mac
p = Path('C:/Users/user/Documents') # Windows
p = Path() # 当前目录2. 路径创建和基本操作
不同方式创建路径
from pathlib import Path
# 绝对路径
abs_path = Path('/home/user/documents/file.txt')
# 相对路径
rel_path = Path('documents/file.txt')
# 当前目录
current_dir = Path('.')
# 家目录
home_dir = Path.home() # 跨平台家目录
# 当前工作目录
cwd = Path.cwd()路径拼接
# 使用 / 操作符(推荐)
path = Path('/home/user') / 'documents' / 'file.txt'
# 使用 joinpath 方法
path = Path('/home/user').joinpath('documents', 'file.txt')
# 拼接多个路径组件
base = Path('/base')
full_path = base / 'dir' / 'subdir' / 'file.txt'3. 路径解析和属性
获取路径组成部分
path = Path('/home/user/documents/file.txt')
# 路径组成部分
print(path.anchor) # '/' (根目录)
print(path.parent) # /home/user/documents
print(path.name) # file.txt
print(path.stem) # file (文件名不含扩展名)
print(path.suffix) # .txt (扩展名)
print(path.suffixes) # ['.txt'] 所有扩展名列表
print(path.drive) # Windows下的驱动器号 (如 'C:')
# 父目录链
for parent in path.parents:
print(parent)
# /home/user/documents
# /home/user
# /home
# /路径检测方法
path = Path('some_file.txt')
print(path.exists()) # 路径是否存在
print(path.is_file()) # 是否是文件
print(path.is_dir()) # 是否是目录
print(path.is_absolute()) # 是否是绝对路径
print(path.is_symlink()) # 是否是符号链接
print(path.is_block_device()) # 是否是块设备
print(path.is_char_device()) # 是否是字符设备
print(path.is_fifo()) # 是否是FIFO
print(path.is_socket()) # 是否是套接字4. 文件系统操作
目录操作
# 创建目录
path = Path('new_directory')
path.mkdir(exist_ok=True) # exist_ok=True 避免目录已存在时报错
# 创建多级目录
deep_path = Path('dir1/dir2/dir3')
deep_path.mkdir(parents=True, exist_ok=True)
# 删除目录(目录必须为空)
path.rmdir()
# 遍历目录
dir_path = Path('/home/user/documents')
# 列出所有条目
for item in dir_path.iterdir():
print(item)
# 使用通配符匹配
for py_file in dir_path.glob('*.py'):
print(py_file)
# 递归匹配
for py_file in dir_path.rglob('*.py'):
print(py_file)
# 列出所有.py文件(递归)
python_files = list(dir_path.glob('**/*.py'))文件操作
# 创建/写入文件
file_path = Path('test.txt')
file_path.write_text('Hello, World!') # 写入文本
file_path.write_bytes(b'Binary data') # 写入二进制
# 读取文件
content = file_path.read_text() # 读取文本
binary_content = file_path.read_bytes() # 读取二进制
# 文件信息
print(file_path.stat()) # 文件状态信息
print(file_path.stat().st_size) # 文件大小
print(file_path.stat().st_mtime) # 修改时间
# 重命名/移动文件
old_path = Path('old_name.txt')
new_path = Path('new_name.txt')
old_path.rename(new_path)
# 删除文件
file_path.unlink(missing_ok=True) # missing_ok=True 避免文件不存在时报错
# 文件权限
file_path.chmod(0o755) # 修改文件权限
















