5. 实用方法和属性
路径修改
path = Path('/home/user/documents/file.txt')
# 修改扩展名
new_path = path.with_suffix('.pdf') # /home/user/documents/file.pdf
# 修改文件名
new_path = path.with_name('newfile.txt') # /home/user/documents/newfile.txt
# 修改父目录
new_path = path.with_parent(Path('/tmp')) # /tmp/file.txt
# 获取相对路径
base = Path('/home/user')
relative = path.relative_to(base) # documents/file.txt路径比较和解析
path1 = Path('/home/user/file.txt')
path2 = Path('/home/user/documents/../file.txt')
print(path1 == path2) # False (字符串比较)
print(path1.resolve() == path2.resolve()) # True (解析后比较)
# 解析路径(消除 .. 和 .)
resolved = path2.resolve() # /home/user/file.txt
# 判断是否为其他路径的子路径
parent = Path('/home/user')
print(path1.is_relative_to(parent)) # True6. 实际应用示例
文件搜索和统计
from pathlib import Path
from collections import Counter
def analyze_directory(directory):
"""分析目录中的文件类型"""
path = Path(directory)
extensions = Counter()
for file_path in path.rglob('*'):
if file_path.is_file():
extensions[file_path.suffix.lower()] += 1
return extensions
# 使用示例
result = analyze_directory('/path/to/directory')
for ext, count in result.most_common():
print(f"{ext or '无扩展名'}: {count} 个文件")批量重命名文件
def batch_rename(directory, pattern, replacement):
"""批量重命名文件"""
path = Path(directory)
for file_path in path.glob('*' + pattern + '*'):
if file_path.is_file():
new_name = file_path.name.replace(pattern, replacement)
new_path = file_path.with_name(new_name)
file_path.rename(new_path)
print(f"重命名: {file_path.name} -> {new_name}")
# 使用示例
batch_rename('./photos', 'IMG', 'Photo')创建项目结构
def create_project_structure(project_name):
"""创建标准的Python项目结构"""
base_dir = Path(project_name)
directories = [
base_dir / 'src' / project_name,
base_dir / 'tests',
base_dir / 'docs',
base_dir / 'scripts'
]
files = [
base_dir / 'README.md',
base_dir / 'requirements.txt',
base_dir / 'setup.py',
base_dir / 'src' / project_name / '__init__.py',
base_dir / 'src' / project_name / 'main.py'
]
# 创建目录
for directory in directories:
directory.mkdir(parents=True, exist_ok=True)
print(f"创建目录: {directory}")
# 创建文件
for file_path in files:
file_path.touch()
print(f"创建文件: {file_path}")
# 使用示例
create_project_structure('my_project')备份文件
from datetime import datetime
import shutil
def backup_files(source_dir, backup_dir, extensions=None):
"""备份指定类型的文件"""
source_path = Path(source_dir)
backup_path = Path(backup_dir)
# 创建带时间戳的备份目录
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_dir = backup_path / f"backup_{timestamp}"
backup_dir.mkdir(parents=True, exist_ok=True)
# 备份文件
for file_path in source_path.rglob('*'):
if file_path.is_file():
if extensions is None or file_path.suffix.lower() in extensions:
relative_path = file_path.relative_to(source_path)
target_path = backup_dir / relative_path
target_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(file_path, target_path)
print(f"备份: {relative_path}")
# 使用示例
backup_files('/important/documents', '/backup', ['.pdf', '.docx', '.txt'])7. 与 os 模块的对比
传统 os.path 方式 vs Pathlib
import os
from pathlib import Path
# 传统方式
path = '/home/user/documents/file.txt'
dirname = os.path.dirname(path)
basename = os.path.basename(path)
filename, ext = os.path.splitext(basename)
# Pathlib 方式
path_obj = Path('/home/user/documents/file.txt')
dirname = path_obj.parent
basename = path_obj.name
filename = path_obj.stem
ext = path_obj.suffix
# 更简洁、更直观常用操作对比
import os
import shutil
from pathlib import Path
# 检查文件是否存在
os.path.exists('file.txt') # 传统
Path('file.txt').exists() # Pathlib
# 创建目录
os.makedirs('path/to/dir', exist_ok=True) # 传统
Path('path/to/dir').mkdir(parents=True, exist_ok=True) # Pathlib
# 连接路径
os.path.join('dir', 'subdir', 'file.txt') # 传统
Path('dir') / 'subdir' / 'file.txt' # Pathlib8. 最佳实践
- 优先使用 Pathlib: 新代码中尽量使用 Pathlib 而不是 os.path
- 链式操作: 利用 Path 对象的链式调用特性
- 异常处理: 适当处理文件操作可能出现的异常
- 路径解析: 使用
resolve()处理包含..和.的路径 - 跨平台兼容: Pathlib 自动处理不同操作系统的路径差异
Pathlib 提供了更现代、更Pythonic的方式来处理文件系统路径,使代码更简洁、更易读。
















