📚 概述
在 Python 中进行文件操作和路径管理是日常开发的基础技能。本文将介绍现代化的路径管理方式 pathlib,以及文件读写的最佳实践。
1️⃣ 使用 pathlib 进行路径管理
pathlib 是 Python 3.4+ 引入的现代化路径处理库,比传统的 os.path 更直观、更易用。
from pathlib import Path
# 创建路径对象
current_dir = Path('.')
project_dir = Path('/home/user/myproject')
# 路径拼接(推荐方式)
config_file = project_dir / 'config' / 'settings.json'
print(config_file) # /home/user/myproject/config/settings.json
# 获取父目录
parent = config_file.parent # /home/user/myproject/config
# 获取文件名和扩展名
print(config_file.name) # settings.json
print(config_file.suffix) # .json
print(config_file.stem) # settings
2️⃣ 文件读取的最佳实践
from pathlib import Path
# 推荐:使用 with 语句自动管理文件关闭
file_path = Path('data.txt')
# 读取全部内容为字符串
content = file_path.read_text(encoding='utf-8')
# 读取全部内容为字节
binary_content = file_path.read_bytes()
# 逐行读取(适合大文件)
with file_path.open('r', encoding='utf-8') as f:
for line in f:
print(line.strip())
# 读取所有行到列表
lines = file_path.read_text(encoding='utf-8').splitlines()
3️⃣ 文件写入的最佳实践
from pathlib import Path
output_path = Path('output/result.txt')
# 确保目录存在
output_path.parent.mkdir(parents=True, exist_ok=True)
# 写入文本(覆盖模式)
output_path.write_text('Hello, World!\n', encoding='utf-8')
# 追加模式
with output_path.open('a', encoding='utf-8') as f:
f.write('追加内容\n')
# 写入字节
output_path.write_bytes(b'binary data')
4️⃣ 目录遍历与文件查找
from pathlib import Path
src_dir = Path('./src')
# 遍历目录下所有文件
for item in src_dir.iterdir():
if item.is_file():
print(f'文件:{item.name}')
elif item.is_dir():
print(f'目录:{item.name}')
# 递归遍历所有子目录
for item in src_dir.rglob('*'):
print(item)
# 查找特定扩展名的文件
python_files = list(src_dir.rglob('*.py'))
print(f'找到 {len(python_files)} 个 Python 文件')
# 查找特定模式的文件
test_files = list(src_dir.rglob('test_*.py'))
5️⃣ 实战:批量文件处理器
from pathlib import Path
import shutil
class BatchFileProcessor:
"""批量文件处理器"""
def __init__(self, source_dir: str, target_dir: str):
self.source = Path(source_dir)
self.target = Path(target_dir)
self.target.mkdir(parents=True, exist_ok=True)
def copy_by_extension(self, ext: str) -> int:
"""按扩展名复制文件"""
count = 0
for file in self.source.rglob(f'*{ext}'):
if file.is_file():
relative_path = file.relative_to(self.source)
dest = self.target / relative_path
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(file, dest)
count += 1
print(f'已复制:{relative_path}')
return count
def get_file_stats(self) -> dict:
"""获取文件统计信息"""
stats = {'total_files': 0, 'total_size': 0, 'by_extension': {}}
for file in self.source.rglob('*'):
if file.is_file():
stats['total_files'] += 1
size = file.stat().st_size
stats['total_size'] += size
ext = file.suffix or '无扩展名'
stats['by_extension'][ext] = stats['by_extension'].get(ext, 0) + 1
return stats
# 使用示例
if __name__ == '__main__':
processor = BatchFileProcessor('./source', './output')
# 复制所有 Python 文件
copied = processor.copy_by_extension('.py')
print(f'复制了 {copied} 个文件')
# 获取统计信息
stats = processor.get_file_stats()
print(f"总文件数:{stats['total_files']}")
print(f"总大小:{stats['total_size'] / 1024:.2f} KB")
💡 关键要点总结
| 操作 | 推荐方法 |
|---|---|
| 路径拼接 | Path / 'subdir' / 'file.txt' |
| 读取文件 | path.read_text(encoding='utf-8') |
| 写入文件 | path.write_text(content, encoding='utf-8') |
| 检查存在 | path.exists() 或 path.is_file() |
| 创建目录 | path.mkdir(parents=True, exist_ok=True) |
| 遍历文件 | path.iterdir() 或 path.rglob('*.py') |
⚠️ 注意事项
- 始终指定编码:读写文本文件时使用
encoding='utf-8' - 使用 with 语句:确保文件正确关闭
- 先创建目录:写入前确保目标目录存在
- 路径跨平台:
pathlib自动处理 Windows/Linux 路径差异 - 大文件处理:使用流式读取,避免一次性加载到内存