【python】pathlib用法
pathlib
组件常用方法全面指南
pathlib
模块提供了一整套面向对象的文件系统路径处理方法,主要包含 Path
类(处理通用路径)以及其子类 PurePath
(纯路径操作)、PurePosixPath
和 PureWindowsPath
(平台特定路径)。以下是核心类 Path
的常用方法分类详解:
1. 路径创建与基础属性
from pathlib import Path# 1. 创建路径对象
current_dir = Path.cwd() # 当前工作目录
home_dir = Path.home() # 用户主目录
absolute_path = Path("/usr/bin/python3") # 绝对路径
relative_path = Path("docs/report.txt") # 相对路径
combined = Path.home() / "Downloads" / "file.zip" # 路径拼接# 2. 获取路径组成部分
path = Path("/home/user/docs/report_final.pdf")
print(path.name) # 'report_final.pdf' 完整文件名
print(path.stem) # 'report_final' 文件名(无扩展名)
print(path.suffix) # '.pdf' 扩展名
print(path.suffixes) # ['.pdf'] 所有扩展名列表
print(path.parent) # Path('/home/user/docs') 父目录
print(path.parents) # 父目录链的可迭代对象(第0级为最近父目录)
print(path.parts) # ('/', 'home', 'user', 'docs', 'report_final.pdf') 路径组成部分
print(path.anchor) # '/' 根目录部分
2. 路径操作与转换
# 1. 路径修改
new_path = path.with_name("summary.pdf") # 替换文件名
new_path = path.with_stem("brief") # Python 3.9+ 替换文件名主体
new_path = path.with_suffix(".txt") # 替换扩展名
new_path = path.relative_to("/home/user") # 获取相对路径:Path('docs/report_final.pdf')# 2. 路径标准化
clean_path = Path("docs/../images/./logo.png").resolve() # 解析符号链接 -> /abs/path/images/logo.png
abs_path = path.absolute() # 获取绝对路径(不解析符号链接)# 3. 连接路径
new_path = path.parent.joinpath("backup", "copy.pdf") # Path('/home/user/docs/backup/copy.pdf')
3. 文件系统查询与检查
# 1. 检查路径属性
print(path.exists()) # 路径是否存在
print(path.is_file()) # 是否是文件
print(path.is_dir()) # 是否是目录
print(path.is_symlink()) # 是否是符号链接
print(path.is_absolute()) # 是否是绝对路径
print(path.is_relative_to("/home")) # Python 3.9+ 是否相对某个路径# 2. 获取文件信息
stats = path.stat()
print(f"大小: {stats.st_size} bytes") # 文件大小
print(f"修改时间: {stats.st_mtime}") # 修改时间戳
print(f"创建时间: {stats.st_ctime}") # 创建时间戳
4. 目录操作
# 1. 目录创建与删除
new_dir = Path("new_directory")
new_dir.mkdir() # 创建单级目录
new_dir.mkdir(parents=True, exist_ok=True) # 递归创建,目录存在不报错
new_dir.rmdir() # 删除空目录# 2. 目录遍历
# 列出目录内容(不递归)
for item in path.parent.iterdir():print(item) # 所有文件和子目录# 查找文件
for py_file in path.parent.glob("*.py"): # 当前目录的.py文件print(py_file)for all_txt in path.parent.rglob("*.txt"): # 递归搜索所有.txt文件print(all_txt)
5. 文件操作
# 1. 文件创建与删除
new_file = Path("temp.txt")
new_file.touch() # 创建空文件
new_file.unlink(missing_ok=True) # 删除文件(文件不存在不报错)# 2. 文件读写
# 文本读写
new_file.write_text("Hello, world!", encoding="utf-8") # 写入文本
content = new_file.read_text(encoding="utf-8") # 读取文本# 二进制读写
binary_data = b'\x89PNG\r\n\x1a\n'
png_file = Path("image.png")
png_file.write_bytes(binary_data) # 写入二进制
data = png_file.read_bytes() # 读取二进制# 3. 文件操作(使用上下文管理器)
with new_file.open("a", encoding="utf-8") as f: # 追加模式f.write("\nAdditional content")
6. 实用高级技巧
# 1. 临时文件处理
import tempfile
with tempfile.TemporaryDirectory() as tmp:temp_dir = Path(tmp)temp_file = temp_dir / "temp.log"temp_file.write_text("Temporary content")# 2. 文件重命名/移动
src = Path("source.txt")
dst = Path("backup/archived.txt")
dst.parent.mkdir(exist_ok=True) # 确保目标目录存在
src.rename(dst) # 移动并重命名文件# 3. 批量修改文件
for txt_file in Path("docs").rglob("*.txt"):new_name = txt_file.with_stem(f"{txt_file.stem}_backup")txt_file.rename(new_name)# 4. 安全路径处理
user_input = input("Enter file path: ")
safe_path = Path(user_input).resolve(strict=False) # 限制路径在安全范围内
7. 与旧版os/os.path互操作
import os# Path -> 字符串
str_path = str(path) # '/home/user/docs/report_final.pdf'# Path <-> os.path
os.chdir(Path("new_dir")) # 修改工作目录
file_size = os.path.getsize(path) # 相当于 path.stat().st_size# 使用Path简化os操作
files = [Path(f) for f in os.listdir(".") if Path(f).is_file()]