一、基本概念
pathlib 是Python 面向对象的 文件路径 处理模块, 替代传统os.path 字符串拼接方式,把 路径本身封装成对象,代码可读性更强,支持跨平台(Windows / Linux /macOS)
核心思想:不再用字符串表示路径,而是路径对象。所有操作调用对象方法,不用手动拼接字符串、处理斜杠正反问题
二、基础导入与核心类
from pathlib import Path
2.1、pathlib 核心路径类
PurePath:pathlib 中的基础纯路径类,仅处理路径字符串操作,不与实际文件系统交互,提供路径解析、拼接、比较等核心功能。PurePosixPath:继承PurePath,专门处理 POSIX 风格(Linux/macOS)路径,强制遵循 Unix 路径规则(如分隔符为/),不涉及系统调用,适合跨平台路径字符串处理;PureWindowsPath:继承PurePath,针对 Windows 系统路径设计,支持盘符、反斜杠分隔符等 Windows 路径特性,仅做字符串层面的路径操作,与实际文件系统无关;Path:pathlib 中的实体路径类,继承PurePath,结合纯路径操作与实际文件系统交互能力,可同时拥有文件读写、判断存在性、创建删除等磁盘操作能力;PosixPath:继承Path、PurePosixPath,适配 POSIX 系统的具体路径实现,封装 Linux/macOS 下的文件系统操作(如权限管理、符号链接处理),继承 PurePosixPath 的路径规则;WindowsPath:继承Path、PureWindowsPath,针对 Windows 系统的具体路径实现,支持 Windows 特有的文件系统功能(如 NTFS 权限、盘符操作),基于 PureWindowsPath 扩展实际 I/O 能力;
2.2、类的层次结构
PurePath 不访问文件系统,因此可在Linux上解析 Windows 路径Path 是平台相关的,Path 在 Linux 上实例化出来就是 PosixPath,在 Windows 上就是 WindowsPath。不能直接实例化 PosixPath/WindowsPath(会检查平台),但可以实例化 PurePosixPath / PureWindowsPath
纯路径 vs 具体路径的选择原则:
只做字符串拼接、解析、格式化,用 PurePath。如生成要发给远端的路径、解析日志里的路径需要 stat / 读写 / 遍历,用 Path
PurePath # 纯路径:只做字符串运算,不碰磁盘
├─ PurePosixPath # 纯Linux路径(不访问磁盘,仅字符串处理)
└─ PureWindowsPath # 纯Windows路径(不访问磁盘,仅字符串处理)
Path # 具体路径:继承 PurePath,可做 IO
├─ PosixPath # Linux/macOS 真实路径(可读写磁盘)
└─ WindowsPath # Windows 真实路径(可读写磁盘)
from pathlib import PurePosixPath, PureWindowsPath, Path
# 跨平台解析:在 Linux 上分析 Windows 路径
w = PureWindowsPath(r"C:\Users\alice\data\file.txt")
print(w.drive, w.root, w.name) # 'C:' '\' 'file.txt'
print(w.parts) # ('C:\\', 'Users', 'alice', 'data', 'file.txt')
p = PurePosixPath("/usr/local/lib")
print(p.parent, p.name) # /usr/local lib
# 当前平台的 Path
print(Path("/tmp")) # PosixPath('/tmp') (Linux)
三、基础使用
3.1、创建 Path 对象
from pathlib import Path
# 创建 Path 对象的几种方式
current_path = Path() # 当前目录相对路径,即脚本所在目录 等于 Path('.')
relative_path = Path("folder/subfolder") # 相对路径
absolute_path = Path("/home/user/folder/subfolder") # 绝对路径(Linux/Mac)
window_path = Path("C:/Users/Administrator/Desktop") # 绝对路径(Windows)
multi_path = Path("/etc", "nginx", "nginx.conf") # 绝对路径 /etc/nginx/nginx.conf
3.2、路径操作
3.2.1、路径拼接
pathlib 使用斜杠运算符 / 来拼接路径,左边必须是 Path 对象。替代传统的 os.path.join() ,可读性强。
# 路径拼接,左侧必须是Path对象,右侧可以是字符串
# 1、使用 / 拼接,支持多级路径拼接,不需要额外的 os.path.join()
base = Path("/home/user")
full_path = base / "data" / "log.txt"
print(full_path) # 输出: /home/user/data/log.txt
# 2、使用 Path对象 / Path对象
sub_dir = Path("data")
file_path2 = base / sub_dir / "test.txt"
print(file_path2) # 输出: /home/user/data/test.txt
# 3、使用 joinpath()拼接,等价写法,接受多个参数
path = Path('/tmp')
file_path3 = path.joinpath('data', 'logs', 'app.log')
print(file_path3) # 输出: /tmp/data/logs/app.log
3.2.2、路径属性拆分
| 属性 | 说明 | 代码示例 | 结果(Unix) |
|---|---|---|---|
| name | 文件名(含后缀) / 目录名 | Path("a/b/c.py").name | 'c.py' |
| stem | 文件名(不含后缀) | Path("a/b/c.tar.gz").stem | 'c.tar' |
| suffix | 文件后缀 | Path("a/b/c.tar.gz").suffix | '.gz' |
| suffixes | 所有后缀列表 | Path("a/b/c.tar.gz").suffixes | ['.tar', '.gz'] |
| parent | 直接父路径 | Path("a/b/c.py").parent | PosixPath('a/b') |
| parents | 祖先路径序列(支持切片和负索引) | Path("a/b/c.py").parents[0] | PosixPath('a/b') |
| root | 根路径 | Path("/etc").root | '/' |
| anchor | 驱动器 + 根路径 | Path("C:/Windows").anchor | Unix: "" 或 windows: 'C:\\' |
| parts | 路径组件元组 | Path("/usr/bin/python3").parts | ('/', 'usr', 'bin', 'python3') |
| drive | 驱动器 / UNC 共享名 | Path("C:/Windows").drive | Unix: "" 或 windows: 'C:' |
from pathlib import Path
path = Path(r'D:\Users\base_demo\demo.py')
""" 获取文件名(包含所有扩展名)"""
full_file_name = path.name # 文件名(含后缀): demo.py
# 获取不带扩展名的文件名
stem_file_name = path.stem # 文件名(不含后缀): demo
# 获取文件后缀
suffix_file_name = path.suffix # 文件后缀: .py
suffix_file_names = path.suffixes # 多后缀列表 archive.tar.gz -> ['.tar', '.gz']
# 获取父目录绝对路径(返回 Path 对象)
parent_directory = path.parent # 父目录: D:/Users/base_demo
base_parent = parent_directory.parent # 父目录的父目录: D:/Users
# 获取所有祖先目录序列,可索引、可切片, 从近到远,直到根目录
for parent in path.parents:
print(parent)
# /home/user/documents # parents[0]
# /home/user # parents[1]
# /home # parents[2]
# / # parents[-1]
first_floor = path.parents[0] # 第一层目录: D:\Users\base_demo
second_floor = path.parents[-1] # 最后一层目录: D:\
# 将路径拆分为元组,包含所有目录和文件名
parts = path.parts # 路径拆分: ('D:\', 'Users', 'base_demo', 'demo.py')
# 获取 根目录 ,Linux `/`,Windows `C:`
anchor = path.anchor # 锚点(驱动器): D:\
# 获取路径根部分,Linux `/`,Windows `C:`
root1 = path.root
3.2.3、路径判断方法
| 方法 | 说明 |
|---|---|
exists(follow_symlinks=True) | 判断路径是否存在(3.12+ 支持控制符号链接) |
is_file() | 判断是否为普通文件(或指向文件的符号链接) |
is_dir() | 判断是否为目录(或指向目录的符号链接) |
is_symlink() | 判断是否为符号链接 |
is_absolute() | 判断是否为绝对路径 |
is_relative_to(other) | 判断是否相对于other路径(3.9+,3.12弃用多参数) |
is_reserved() | 判断是否为 Windows 保留路径(Unix 始终返回False) |
samefile(other_path) | 判断是否与other_path指向同一文件(3.5+) |
is_junction() | 判断是否为 Windows 接合点(3.12+) |
is_mount() | 判断是否为挂载点(3.7+,3.12+ 支持 Windows) |
is_socket() | 判断是否为 Unix 套接字文件 |
is_fifo() | 判断是否为 FIFO 管道文件 |
is_block_device() | 判断是否为块设备 |
is_char_device() | 判断是否为字符设备 |
file_path = Path(r"/etc/host/demo.py")
dir_path = Path(r"/etc/host")
# 判断文件或目录是否存在
print("判断文件或目录是否存在", file_path.exists())
# 判断是否是文件或目录
print("判断是否是目录", dir_path.is_dir())
print("判断是否是文件", file_path.is_file())
# 判断是否是绝对路径
print("判断是否是绝对路径:", file_path.is_absolute())
# 判断是否是相对路径
# 判断 file_path 是否是 dir_path 的相对路径
print("判断路径是否为指定路径的相对路径:", file_path.is_relative_to(dir_path)) # 即 file_path 是否在 dir_path 下层
print("判断路径是否为指定路径的相对路径:", dir_path.is_relative_to(file_path)) # 即 dir_path 是否在 file_path 下层
# 判断是否是符号链接,即软链接
print("判断是否是符号链接:", file_path.is_symlink())
print("判断路径是否为FIFO管道:", file_path.is_fifo())
print("判断路径是否为挂载点:", file_path.is_mount())
print("判断路径是否为套接字文件:", file_path.is_socket())
print("判断路径是否为绝对路径:", file_path.is_absolute())
print("判断路径是否为块设备文件:", file_path.is_block_device())
print("判断路径是否为字符设备文件:", file_path.is_char_device())
print("判断路径是否为Windows目录连接点:", file_path.is_junction())
# 真正的目录
print("判断路径是否为真正的目录:", dir_path.is_dir() and not dir_path.is_symlink())
3.2.3、路径操作方法
| 方法 | 说明 | 代码示例 |
|---|---|---|
joinpath(*pathsegments) | 拼接路径(等价于/运算符) | Path("/etc").joinpath("passwd") → /etc/passwd |
with_name(name) | 修改文件名(保留路径) | Path("a/b/c.py").with_name("d.txt") → a/b/d.txt |
with_stem(stem) | 修改文件名(保留后缀,3.9+) | Path("a/b/c.tar.gz").with_stem("e") → a/b/e.gz |
with_suffix(suffix) | 修改后缀(空字符串移除后缀) | Path("a/b/c.py").with_suffix(".txt") → a/b/c.txt |
with_segments(*pathsegments) | 重构路径组件(3.12+) | Path("a/b/c").with_segments("x", "y") → x/y |
relative_to(other, walk_up=False) | 计算相对路径(3.12+ 支持walk_up=True生成…/) | Path("/etc/passwd").relative_to("/usr", walk_up=True) → ../etc/passwd |
match(pattern,case_sensitive=None) | 匹配 glob 模式(3.12+ 支持大小写控制) | Path("a/b.py").match("*.py") → True |
expanduser() | 扩展和user路径(3.5+) | Path("~/docs").expanduser() → /home/user/docs |
absolute() | 转为绝对路径(不解析符号链和.) | Path("a/b").absolute() → /current/dir/a/b |
resolve(strict=False) | 绝对化并解析符号链接/.(3.6+ 支持strict) | Path(“docs/…/setup.py”).resolve() → /current/dir/setup.py |
readlink() | 返回符号链接指向的路径(3.9+) | Path(“mylink”).readlink() → setup.py |
"""
计算相对路径:
relative_to 的作用是:把一个绝对路径转换成相对于某个基准路径的"相对路径"。
"""
源目录: /data/source
子目录: /data/source/a/b/c
path = Path("/data/source/a/b/c")
base = Path("/data/source")
print(path.relative_to(base)) # 输出: a/b/c
就是把 /data/source 这个"前缀"剥掉,得到剩余的相对部分 a/b/c。
举例:
递归复制源目录下的所有子目录结构到目标位置,但不会复制任何文件内容
source_folder = Path("/data/source")
targe_folder = Path("/data/target/")
源目录: /data/source/
├── a/
│ └── b/
└── x/
└── y/
└── z/
目标目录: /data/target/ (要还原同样的结构)
# 遍历到 /data/source/x/y/z 时:
# 1. 算出相对路径: x/y/z
relative = dir_path.relative_to(source_path)
# 2. 拼接到目标: /data/target + x/y/z = /data/target/x/y/z
target_subdir = target_path / relative
# 3. 创建目录
target_subdir.mkdir(parents=True, exist_ok=True)
# 为什么不用绝对路径?
因为目标目录和源目录通常不在同一个位置,如果直接用绝对路径 /data/source/x/y/z,就会在错误的地方创建目录,而不是在 /data/target/ 下面。
from pathlib import Path
"""
绝对路径 和 相对路径 转换
resolve() 和 absolute()区别:
- absolute():只拼接 cwd 后得到绝对路径,不解软链接,相当于 path.getcwd() + path
- resolve():解析符号链接,返回操作系统真实物理路径
"""
# 创建 path 对象 绝对路径
# path = Path(__file__).parent / "input.txt"
path = Path("/home/zkc/test_dir/real_file.txt")
# 返回绝对路径,自动解析软链接。strict=True 时路径不存在会抛异常
resolve_path = path.resolve(strict=False)
print("resolve绝对路径: ", resolve_path)
# 获取绝对路径,**不解析软链接**
absolute_path = path.absolute()
print("absolute绝对路径: ", absolute_path)
# 创建 path 对象 相对路径
path1 = Path('../test_dir/./real_file.txt')
print("原始路径:", path1) # 输出:../test_dir/./real_file.txt
print("resolve():", path1.resolve(strict=False)) # 解析../和./ 以及软链接,返回真实绝对路径
print("absolute():", path1.absolute()) # 仅补全当前目录,转绝对路径,保留../和./
print("as_posix:", path1.as_posix())
print("转字符串:", str(path1))
"""
修改文件名 / 后缀,返回新对象,原对象不变
"""
# 实际应用:替换文件扩展名
file = Path('report.xlsx')
new_file = file.with_suffix('.pdf')
print(new_file) # report.pdf
# 修改文件名
old = Path('data/old_name.txt')
new = old.with_name('new_name.txt')
print(new) # data/new_name.txt
# 无后缀时 with_suffix 是“追加”
Path("/srv/README").with_suffix(".md") # PosixPath('/srv/README.md')
# 组合使用
config = Path('/etc/nginx/nginx.conf')
backup = config.with_name(config.stem + '.backup' + config.suffix)
print(backup) # /etc/nginx/nginx.backup.conf
# with_name/with_suffix 在根路径上会报错
Path("/").with_name("x") # ValueError
print(Path.cwd()) # 当前工作目录,绝对路径
# Path.home() 和 Path("~").expanduser() 是等价的。它们都指向用户主目录。
print(Path.home()) # 当前用户家目录,绝对路径
print(Path("~").expanduser()) # 当前用户家目录,绝对路径
3.3、目录操作
| 方法 | 说明 | 代码示例 |
|---|---|---|
iterdir() | 遍历目录下的文件/子目录(不递归) | [x for x in Path(“.”).iterdir() if x.is_dir()] |
rename(target) | 重命名文件/目录(3.8+ 返回新Path) | Path(“old.txt”).rename(“new.txt”) → PosixPath(‘new.txt’) |
replace(target) | 重命名文件/目录(无条件覆盖,3.8+ 返回新Path) | Path(“old.txt”).replace(“exist.txt”) |
glob(pattern, case_sensitive=None) | 匹配目录下的文件(支持**递归,3.12+ 支持大小写控制) | list(Path(“.”).glob(“**/*.py”)) → 所有Python文件 |
rglob(pattern, case_sensitive=None) | 递归匹配(等价于glob("**/pattern"),3.12+ 支持大小写控制) | list(Path(“.”).rglob(“*.txt”)) → 所有子目录的TXT文件 |
walk(top_down=True, on_error=None, follow_symlinks=False) | 递归遍历目录树(3.12+) | for root, dirs, files in Path(“project”).walk(): … |
touch(mode=0o666, exist_ok=True) | 创建空文件(已存在则更新修改时间) | Path(“new.txt”).touch() |
unlink(missing_ok=False) | 删除文件 / 符号链接(3.8+ 支持missing_ok) | Path(“a.txt”).unlink(missing_ok=True) |
mkdir(mode=0o777, parents=False, exist_ok=False) | 创建目录(parents=True递归创建父目录,3.5+ 支持exist_ok) | |
rmdir() | 删除空目录(目录非空则报错) | Path(“empty_dir”).rmdir() |
symlink_to(target, target_is_directory=False) | 创建符号链接(Windows需指定目标类型) | Path(“link”).symlink_to(“target.py”) |
| hardlink_to(target) | 创建硬链接(3.10+) | Path(“hardlink”).hardlink_to(“target.py”) |
3.3.1、创建/删除目录
parents=False:是否自动递归创建多级父目录。parents=True等价mkdir -pexist_ok=False:目录已存在时报错;exist_ok=True,目录存在也不抛异常只能删除空文件夹,文件夹内有文件会抛出异常- 创建目录时,
目标路径不能是文件,否则抛出异常 - 删除目录时,
只能删除空文件夹,文件夹内有文件会抛出异常
from pathlib import Path
# 1、 创建单层目录,exist_ok=False 目录已存在会报错;exist_ok=True 目录已存在不会报错
path = Path(__file__).parent / "zkc"
path.mkdir(exist_ok=True)
# 2、创建多层目录,parents=True 递归创建父目录
path2 = Path(__file__).parent / "zkc" / "test" / "a" / "b" / "c"
path2.mkdir(parents=True, exist_ok=True)
# 3、删除空目录,目录必须为空
path3 = Path("/tmp/zkc")
if path3.exists() and path3.is_dir():
path3.rmdir()
# 4、删除非空目录。pathlib 原生不支持,需要 `shutil.rmtree()`
import shutil
shutil.rmtree("/opt/zkc") # 递归删除目录及其所有内容
3.3.2、目录的移动/重命名
- replace():路径重命名为目标路径,若目标路径已存在则覆盖
- rename():路径重命名为目标路径,目标存在直接抛
FileExistsError,不会覆盖
- 文件 replace
- 同目录:就是重命名
- 不同目录:移动;目标存在直接覆盖文件
- 目录 replace
- 同目录:目录重命名
- 跨目录:移动整个目录树
- ❗致命限制:目标路径不能是一个非空目录,否则报错。
- 跨磁盘 / 分区:
rename()目标不能跨磁盘;replace()支持跨分区移动,存在则覆盖 - 平台差异:Linux 可以替换已存在空目录
from pathlib import Path
# ========== 1、目录 rename() 场景 ==========
old_dir = Path("zkc")
old_dir.mkdir(exist_ok=True)
# 目录重命名
new_dir = old_dir.rename("zkc_new")
# 目录移动
new_dir = old_dir.rename("zkc_new/zkc")
# 目录移动并重命名
new_dir = old_dir.rename("zkc_new/zkc1")
# ========== 2、目录 replace() 场景 ==========
# 准备源目录,并放入一个文件
src_dir = Path("zkc")
src_dir.mkdir(exist_ok=True)
(src_dir / "file.txt").write_text("dir content")
# 1、目录重命名
new_dir = src_dir.replace("zkc")
# 2、目录移动,目录名不变,移动到其他目录
other_dir = Path("dir_parent")
other_dir.mkdir(exist_ok=True)
now_dir = new_dir.replace(other_dir / "zkc")
old_dir = Path("zkc")
new_dir = old_dir.replace("zkc/zkc")
# 3、目录移动并重命名
old_dir = Path("zkc")
new_dir = old_dir.replace("zkc/zkc1")
3.3.3、遍历和匹配目录
iterdir():只遍历当前目录下直接子项,包含文件夹、文件。不递归,返回 Path 对象生成器- 输出顺序由文件系统决定,需要指定顺序请自行排序
glob(pattern):只在当前目录匹配,不递归,返回 Path 对象生成器rglob(pattern):递归所有子目录,返回 Path 对象生成器- 等价于 glob(“
**/pattern”),r = recursive glob
- 等价于 glob(“
match(pattern):用于检查路径是否与给定的模式匹配,从路径的右端开始匹配,适用于检查文件扩展名或特定路径结构,返回bool值- 重点:
从右往左匹配的是【路径末尾片段】,不是完整绝对路径
- 重点:
full_match(pattern):必须整条路径完全匹配 pattern,不是尾部匹配walk():面向对象遍历目录树,返回 Path 对象生成器- Path.walk(top_down=True, on_error=None, follow_symlinks=False)
top_down=True:默认从上往下遍历。设False从底层子目录往上遍历;top_down 模式下修改dirnames列表可以剪枝(跳过某些子目录)on_error:回调函数,接收OSError异常对象,遍历遇到权限 / 不存在报错时触发follow_symlinks=False:是否跟随符号链接,默认不跟随,防止循环链接死循环
- Python3.12+ 新增方法,替代传统
os.walk(), - 迭代产出三元组:
(dirpath: Path, dirnames: list[str], filenames: list[str])dirpath:Path 对象,当前正在遍历的目录dirnames:该目录下子目录名称字符串列表filenames:该目录下文件名称字符串列表
- Path.walk(top_down=True, on_error=None, follow_symlinks=False)
- glob() / rglob() 模式匹配通配符规则:
*:匹配任意字符(不含分隔符/)?:匹配单个字符[abc]:匹配 a/b/c 中任意一个**:递归遍历所有子目录
- glob() / rglob() 注意项:
- glob() / rglob():通配符
*不会匹配.开头隐藏文件 - glob() / rglob():遍历磁盘文件,返回
生成器,多次遍历会失效,想要多次用需要转list() rglob()不写**/*.txt,直接写*.txt即可,内部自带**/glob():写**/*.txt,代表递归所有子目录
- match() 模式匹配通配符规则:
*:匹配任意字符(不含分隔符/)?:匹配单个字符[abc]:匹配 a/b/c 中任意一个
- match() 注意项:
match():不访问磁盘,只是对单个 Path 对象字符串做模式校验,返回布尔值- 只要路径尾部能匹配上 pattern 就返回 True
- walk() 注意项:
Path.walk()的dirpath是 Path 实例,直接/拼接路径,不用os.path.joindirnames和filenames只是名称字符串,不是 Path 对象,必须用dirpath / name得到完整路径- top_down=False 时修改 dirnames无效,不能剪枝
from pathlib import Path
# ========== 1、iterdir() 遍历当前目录 ==========
current_path= Path(".") # 当前目录相对路径,相当于 Path()
for item in current_path.iterdir():
if item.is_file():
print(f"文件:{item}")
elif item.is_dir():
print(f"目录:{item}")
# iterdir() 不递归搜索,若需要自定义顺序输出,则需要自行排序
files = sorted(current_path.iterdir(), key=lambda p: p.name)
for file in files:
print(file)
# ========== 2、glob() / rglob() 模式匹配==========
# 返回的是 “生成器”对象,需要转换为列表,通过for循环遍历
root = Path("/srv/project")
# 1、查找当前目录下所有.py
list(root.glob("*.py")) # 当前层
# 2、查找src目录下所有.py
list(root.glob("src/*.py")) # 一层子目录,只遍历src目
# 3、递归遍历src目录下所有.py
list(root.glob("src/**/*.py")) # 递归遍历src目录下的所有层
# 3、递归遍历当前目录下所有的.py
list(root.glob("**/*.py")) # 递归遍历所有层
# 4、递归遍历当前目录下所有的.py
list(root.rglob("*.py")) # 递归遍历所有层,等价于上一行 root.glob("**/*.py")
# 举例:for循环 迭代生成器对象
for file in root.rglob("*.py"):
print(file)
# 过滤:只匹配文件名包含test的py文件
files = [file for file in root.rglob("*.py") if "path" in file.stem]
# 过滤:只匹配文件,排除文件夹
files = [file for file in root.rglob("*") if file.is_file()]
# 查找名字带数字的文件
files = [file for file in Path("data").glob("file[0-9].txt")]
# ========== 3、match() — 从右往左的模式匹配==========
# match() 方法用于检查路径是否与给定的模式匹配。与 glob() 不同,match() 从路径的右端开始匹配,适用于检查文件扩展名或特定路径结构。
path = Path("/a/b/c/test.txt")
# 从右往左匹配,*表示任意字符
print(path.match("*.txt")) # True,末尾是text.txt
print(path.match("test.txt")) # True,完全匹配
print(path.match("c/*.txt")) # True,路径尾部 c/test.txt 匹配
print(path.match("b/c/*.txt")) # True,路径尾部 b/c/test.txt 匹配
print(path.match("a/b/c/*.txt")) # True,路径尾部 a/b/c/test.txt 匹配
print(path.match("**/*.txt")) # True,任意层级 a/b/c/test.txt 匹配,等价于 rglob("*.txt")
# 不匹配
print(path.match("*.py")) # False, 末尾不是 .py
print(path.match("b/*.txt")) # False,末尾不是 b/xxx.txt
# 匹配目录
p = Path("data/logs")
print(p.match("logs")) # True
print(p.match("data/logs")) # True
# match 结合 rglob 进行文件过滤
files = [
file for file in Path(".").rglob("*")
if file.is_file() and file.match("*.py")
]
print(files)
# ========== 4、full_match() 从左往右的完整路径匹配,python 3.13+==========
p = Path("/srv/project/src/main.py")
p.full_match("**/*.py") # True 完整匹配(类似 glob 的语义)
p.full_match("/srv/**/*.py") # True
p.full_match("*.py") # False 因为要匹配整条路径
# ========== 5、walk() — 自顶向下/自底向上递归遍历目录树,python 3.12+==========
root = Path("./test_dir")
# 自顶向下(默认,先处理父目录再处理子目录,如备份整个目录结构):
# 遍历目录树
for dirpath, dirnames, filenames in root.walk():
print("当前目录:", dirpath)
print("子目录列表:", dirnames)
print("文件列表:", filenames)
# 剪枝:就地修改 dirnames 可以阻止继续深入
dirnames[:] = [d for d in dirnames if d not in {".git", "__pycache__"}]
for name in filenames:
if name.endswith(".py"):
print(dirpath / name)
# 跳过 __pycache__ 目录
if "__pycache__" in dirnames:
dirnames.remove("__pycache__")
print(f"目录 {root}:{len(files)} 个文件,{len(dirnames)} 个子目录")
# 拼接完整路径
for fname in filenames:
file_full = dirpath / fname
print("文件完整路径:", file_full)
# 自底向上(适合先处理子目录再处理父目录,如计算目录大小):
sizes = {}
for dirpath, dirnames, filenames in root.walk(top_down=False):
total = sum((dirpath / f).stat().st_size for f in filenames if (dirpath / f).is_file())
total += sum(sizes[dirpath / d] for d in dirnames if (dirpath / d) in sizes)
sizes[dirpath] = total
3.4、文件操作
| 方法 | 说明 | 代码示例 |
|---|---|---|
read_text(encoding=None,errors=None) | 读取文本内容(3.5+) | Path("a.txt").read_text() → '文件内容' |
write_text(data, encoding=None, **kwargs) | 写入文本(覆盖现有文件,3.5+) | Path("a.txt").write_text("新内容") → 返回字节数 |
read_bytes() | 读取二进制内容(3.5+) | Path("a.bin").read_bytes() → b'二进制数据' |
write_bytes(data) | 写入二进制(覆盖现有文件,3.5+) | Path("a.bin").write_bytes(b'新数据') → 返回字节数 |
open(mode='r', **kwargs) | 打开文件(等价于内置open) | with Path("a.txt").open() as f: f.read() |
stat(follow_symlinks=True) | 获取文件状态(3.10+ 支持控制符号链接) | Path("a.txt").stat().st_size → 文件大小 |
lstat() | 获取文件状态(不跟随符号链接) | Path("mylink").lstat() → 符号链接本身的状态 |
owner() | 返回文件所有者用户名 | Path("a.txt").owner() → 'user' |
group() | 返回文件所属组名 | Path("a.txt").group() → 'users' |
chmod(mode, follow_symlinks=True) | 修改文件权限(3.10+ 支持控制符号链接) | Path("a.txt").chmod(0o444) → 只读权限 |
lchmod(mode) | 修改符号链接权限(不跟随目标) | Path("mylink").lchmod(0o777) |
3.4.1、文件的创建和删除
.touch(mode=0o666, exist_ok=True)创建空文件- exist_ok=False:文件存在抛异常。默认为 True
unlink(missing_ok=False)删除文件- missing_ok=True:文件不存在不报错
# 1、创建空文件,父路径不存在则报错
new_file = Path("zkc/temp.txt")
new_file.touch()
# 2、删除文件
file = Path("zkc/temp.txt")
if file.exists() and file.is_file():
file.unlink()
# 简化写法
# missing_ok=True ,文件不存在不报错
# missing_ok=False,文件不存在则报错
file.unlink(missing_ok=True)
# 以下两种写法效果完全相同
os.remove("example.txt")
os.unlink("example.txt")
3.4.2、文件的 移动/重命名
- replace():路径重命名为目标路径,若目标路径已存在则覆盖
- rename():路径重命名为目标路径,目标存在直接抛
FileExistsError,不会覆盖
- 文件 replace
- 同目录:就是重命名
- 不同目录:移动;
目标存在直接覆盖文件
- 目录 replace
- 同目录:目录重命名
- 跨目录:移动整个目录树
- ❗致命限制:目标路径不能是一个非空目录,否则报错。
- 跨磁盘 / 分区:
rename()目标不能跨磁盘;replace()支持跨分区移动,存在则覆盖 - 平台差异:Linux 可以替换已存在空目录
from pathlib import Path
# ========== 1、文件 rename() 场景 ==========
# 文件重命名
old_file = Path("zkc/test.txt")
new_file = old_file.rename("zkc/test.txt")
# 文件移动
old_file = Path("zkc/test.txt")
new_file = old_file.rename("zkc_new/test.txt")
# 文件移动并重命名
old_file = Path("zkc/test.txt")
new_file = old_file.rename("zkc_new/new_test.txt")
# ========== 2、文件 replace() 场景 ==========
# 准备源文件,并写入内容
src_file = Path("file.txt")
src_file.write_text("hello")
# 1、文件重命名
new_file = src_file.replace("file_new.txt")
# 2、文件移动,存在则覆盖
other_dir = Path("zkc")
other_dir.mkdir(exist_ok=True)
now_file = new_file.replace(other_dir / "file_new.txt")
# 3、文件移动并重命名
other_dir = Path("zkc")
other_dir.mkdir(exist_ok=True)
now_file = new_file.replace(other_dir / "file_1.txt")
Path("file_dst/test_renamed.txt").replace("file_dst/new_test.txt")
3.4.3、获取文件元信息
from pathlib import Path
p = Path(__file__)
stat = p.stat()
# 基础文件属性
print("文件大小(字节):", stat.st_size)
print("索引节点号:", stat.st_ino)
print("设备ID:", stat.st_dev)
print("硬链接数:", stat.st_nlink)
print("用户ID:", stat.st_uid)
print("组ID:", stat.st_gid)
print("文件类型/权限:", stat.st_mode)
# 时间属性(时间戳)
# print ("创建时间(部分系统支持,如 macOS/Windows):", stat.st_birthtime)
# print ("创建时间(纳秒级,部分系统支持):", stat.st_birthtime_ns)
print("创建时间:", stat.st_ctime)
print ("创建时间纳秒级(时间戳):", stat.st_ctime_ns)
print("最后访问时间:", stat.st_atime)
print ("最后访问时间(纳秒级时间戳):", stat.st_atime_ns)
print("最后修改时间:", stat.st_mtime)
print ("最后修改时间(纳秒级时间戳):", stat.st_mtime_ns)
print ("stat_result 对象包含的字段总数:", stat.n_fields)
print ("stat_result 对象可作为序列访问的字段数量:", stat.n_sequence_fields)
print ("stat_result 对象无名称的字段数量:", stat.n_unnamed_fields)
# Unix特有属性
# print("块大小:", stat.st_blksize)
# print("占用块数:", stat.st_blocks)
# print("设备类型(特殊文件):", stat.st_rdev)
# print ("设备号(仅字符 / 块设备文件有效):", stat.st_rdev)
3.4.4、文件的读写
| 方法 | 说明 |
|---|---|
p.read_text(encoding="utf-8", errors=None) | 读取文本文件,返回字符串 |
p.write_text(content, encoding="utf-8") | 写入文本,覆盖原有内容 |
p.read_bytes() | 读取二进制,bytes 对象(图片、压缩包) |
p.write_bytes(b_content) | 写入二进制 |
with p.open("r", encoding="utf-8") | 大文件流式读取,不直接使用 read_text/read_bytes |
注意:
- 大文件不推荐一次性读入内存,使用
with open()流式读取 - write_text 会直接覆盖文件,文件不存在会创建,追加模式要使用
.open(mode="a"): - with p.open 等价内置 open,支持上下文管理器
from pathlib import Path
# ========== 1、文本写入 ==========
path = Path("test.txt")
path.write_text("Hello World", encoding="utf-8")
# ========== 2、文本读取 ==========
content = path.read_text(encoding="utf-8")
print(content)
# ========== 3、二进制读写 ==========
img_path = Path("test.png")
dst_path = Path("copy.png")
data = img_path.read_bytes()
dst_path.write_bytes(data)
bin_path = Path('data.bin')
bin_path.write_bytes(b'\x00\x01\x02\x03')
print(bin_path.read_bytes()) # b'\x00\x01\x02\x03'
# ========== 4、大文件流式读取和写入 ==========
# 使用open方法(更细粒度的控制)
big_file_path = Path("big_log.txt")
with big_file_path.open('a', encoding='utf-8') as f: # 追加模式
f.write('\nAppended text')
with big_file_path.open("r", encoding="utf-8") as file:
for line in file:
print(line.strip())
3.4.5、相对路径和绝对路径
- relative_to ():获取从基准目录到目标路径的相对路径
# 获取绝对路径
print(path.absolute()) # /home/user/project/test.txt
print(path.resolve()) # 解析符号链接后的绝对路径
# 获取相对路径
base = Path("/home/user")
target = Path("/home/user/docs/report.pdf")
rel_path = target.relative_to(base)
print(rel_path) # docs/report.pdf
四、与 os 模块的对应关系
| os.path 函数 | 说明 | pathlib 替代方案 | 替代方案说明 |
|---|---|---|---|
os.path.dirname(path) | 返回路径的目录部分 | Path(path).parent | 获取路径的直接父目录 |
os.path.basename(path) | 返回路径的最后一个组件(文件名/目录名) | Path(path).name | 获取路径的最后一个组件 |
os.path.splitext(path) | 拆分文件名与后缀(返回元组 (stem, suffix)) | Path(path).stem / Path(path).suffix | stem 为文件名(不含后缀),suffix 为最后一个后缀 |
os.path.join(a, b) | 拼接多个路径组件 | Path(a) / b 或 Path(a).joinpath(b) | 支持运算符 / 或 joinpath 方法拼接路径 |
os.listdir(path) | 列出目录下的所有条目(返回字符串列表) | list(Path(path).iterdir()) | 返回目录下所有条目的 Path 对象列表 |
os.mkdir(path) / os.makedirs(path) | 创建单个目录 / 递归创建目录(含父目录) | Path(path).mkdir() | 支持 parents=True 递归创建父目录 |
os.symlink(target, link) | 创建符号链接(link 指向 target) | Path(link).symlink_to(target) | 创建指向 target 的符号链接 |
os.rename(src, dst) | 重命名或移动文件/目录 | Path(src).rename(dst) | 重命名或移动路径到目标位置 |
os.remove(path) / os.unlink(path) | 删除文件(remove 与 unlink 功能相同) | Path(path).unlink() | 删除文件(支持 missing_ok=True 忽略不存在的文件) |
os.rmdir(path) | 删除空目录 | Path(path).rmdir() | 删除空目录(目录非空时抛出错误) |
os.path.isabs(path) | 判断路径是否为绝对路径 | Path(path).is_absolute() | 检查路径是否为绝对路径 |
os.path.relpath(path, start) | 计算从 start 到 path 的相对路径 | Path(path).relative_to(start) | 生成相对于 start 路径的相对路径 |
os.path.expanduser(path) | 扩展路径中的 ~(用户主目录)和 ~user | Path(path).expanduser()/Path.home() | 解析路径中的用户主目录占位符 |
os.path.realpath(path) | 返回解析符号链接后的绝对路径 | Path(path).resolve() | 绝对化路径并解析符号链接和 … |
os.path.abspath(path) | 返回路径的绝对路径(不解析符号链接) | Path(path).absolute() | 转换为绝对路径(保留符号链接和 …) |
os.walk(path) | 递归遍历目录树(生成 (dirpath, dirnames, filenames)) | Path(path).walk() | 递归生成目录树中的所有 Path 对象 |
os.walk(path) | 递归遍历目录树(生成 (dirpath, dirnames, filenames)) | Path(path).walk() | 递归生成目录树中的所有 Path 对象 |
os.path.isfile(p) | 判断是否是文件 | Path(p).is_file() | 判断是否是文件 |
os.path.isdir(p) | 判断是否是文件 | Path(p).is_dir() | 判断是否是目录 |
五、简单案例
5.1、批量修改目录下所有文件后缀(扩展名)
需求:把 data 目录下所有 .txt 改成 .md
from pathlib import Path
# 批量修改目录下所有文件后缀
def change_suffix(file_path: str, old_suffix: str, new_suffix: str):
"""
需求:把 zkc 目录下所有 `.txt` 改成 `.md`
"""
dir_path = Path(file_path)
# 1、使用 iterdir 遍历,`.txt` 改成 `.md`
for file_path in dir_path.iterdir():
if file_path.is_file() and file_path.suffix == f".{old_suffix}":
new_file= file_path.with_suffix(f".{new_suffix}")
file_path.rename(new_file)
print(f"已修改:{file_path.name} -> {new_file.name}")
# 2、使用 glob 遍历,`.md` 改成 `.txt`
for file_path in dir_path.glob(f"*.{new_suffix}"):
new_file = file_path.with_suffix(f".{old_suffix}")
file_path.rename(new_file)
print(f"重命名:{file_path.name} -> {new_file.name}")
if __name__ == '__main__':
change_suffix('zkc', 'txt', 'md')
5.2、递归清理日志,删除大于 100MB 的 log 文件
def delete_large_log_files(directory):
dir_path = Path(directory)
for log_file in dir_path.rglob("*.log"):
if log_file.is_file():
file_size = log_file.stat().st_size / (1024 * 1024) # 转换为 MB
if file_size > 100:
log_file.unlink()
print(f"已删除大日志: {log_file}, size: {file_size:.2f}MB")
if __name__ == '__main__':
delete_large_log_files(__file__)
5.3、递归删除非空文件夹(手工实现)
需求:rmdir 只能删空目录,手写实现递归删除目录的工具函数
from pathlib import Path
# 递归删除非空文件夹
def remove_dir_recursive(dir_path: Path):
assert dir_path != Path('/'), '不能删除根目录'
# 如果路径不存在直接返回
if not dir_path.exists():
return
# 如果是文件直接删除
if dir_path.is_file():
dir_path.unlink()
print(f'删除文件:{dir_path}')
return
# 递归删除所有子文件夹和文件
for item in dir_path.iterdir():
print(f'正在处理:{item}')
# 递归删除子目录中内容
# 如果传入文件,重新调用函数会删除文件
# 如果传入文件夹,会继续向下递归
remove_dir_recursive(item)
print(f'删除文件夹:{dir_path}')
dir_path.rmdir()
if __name__ == '__main__':
path = Path('zkc1')
remove_dir_recursive(path)
5.4、整理文件到日期命令的目录
需求:按文件修改日期整理文件到子目录
import shutil
from pathlib import Path
from datetime import datetime
target_dir = 'zkc'
# 整理文件到日期目录
def organize_files_by_date(dst_dir: str):
"""
按文件修改日期整理文件到子目录
本例是按天整理文件
"""
base_path = Path(dst_dir)
try:
for file_path in base_path.iterdir():
if not file_path.is_file():
continue
# 获取文件的修改时间
modify_time = datetime.fromtimestamp(file_path.stat().st_mtime) # 输出:2026-09-28 15:30:45.123456
# 拼接以修改日期结尾的路径
# 格式化日期:modify_time.strftime('%Y/%m') 输出:2026/09/28
data_dir = base_path / modify_time.strftime('%Y/%m/%d')
# 创建以日期命名的目录
data_dir.mkdir(parents=True, exist_ok=True)
# 目标文件路径
dest_path = data_dir / file_path.name # 输出:XXX/2026/09/28/test.txt
# 移动文件,使用同文件系统或者跨系统【通用】
shutil.move(file_path, dest_path)
# 使用同文件系统
# file_path.rename(dest_path)
print(f"已整理文件: {file_path} -> {dest_path}")
except Exception as e:
print(f"按日期整理文件失败: {e}")
raise
if __name__ == '__main__':
organize_files_by_date(target_dir)
5.5、日志归档脚本
需求:遍历 logs 目录,找到所有 .log 文件,移动到 backup 目录,文件名增加时间后缀。
import shutil
from pathlib import Path
from datetime import datetime
root = 'logs'
backup_dir = 'logs_backup'
# 日志归档脚本
def log_archive(src_dir: str, target_dir: str):
"""
按文件修改日期整理文件到子目录
"""
base_path = Path(src_dir)
backup_path = Path(target_dir)
# 创建备份目录,只创建一次,不用放到循环中
backup_path.mkdir(parents=True, exist_ok=True)
try:
for file_path in base_path.glob('*.log'):
if not file_path.is_file():
continue
# 获取当前时间
time_stamp = datetime.now().strftime('%Y%m%d')
# 归档后的文件名后面 需拼接时间戳
new_name = f'{file_path.stem}_{time_stamp}{file_path.suffix}' # 输出:access.log
# 拼接 备份后的文件路径
dest_file = backup_path / new_name # 输出:logs_backup\access.log
# 移动文件,使用同文件系统或者跨系统【通用】
# shutil.move(file_path, dest_file)
# 使用相同文件系统
file_path.replace(dest_file)
print(f"已归档文件: {file_path} -> {dest_file}")
except Exception as e:
print(f"归档文件失败: {e}")
raise
if __name__ == '__main__':
log_archive(root, backup_dir)
六、pathlib常用场景演示
6.1、常用场景罗列
| 场景类别 | 场景描述 | 预期输出 |
|---|---|---|
| 文件夹列表获取 | 获取直接子文件夹名称 | 返回直接子文件夹的名称列表 |
| 获取所有子文件夹路径 | 返回所有子文件夹的 Path 对象列表 | |
| 文件列表获取 | 获取直接子文件名称(含扩展名) | 返回直接子文件的名称列表(带后缀) |
| 获取所有子文件名称(无扩展名) | 返回所有子文件的名称列表(无后缀) | |
| 获取所有子文件路径 | 返回所有子文件的 Path 对象列表 | |
| 条件筛选 | 按字符串逻辑与(AND)筛选文件夹路径 | 返回满足所有筛选条件的文件夹路径列表 |
| 按字符串逻辑或(OR)筛选文件路径 | 返回满足任一筛选条件的文件路径列表 | |
| 文件夹操作 | 清空目标文件夹 | 删除目标文件夹内所有内容并重建空文件夹 |
| 复制目录结构 | 在目标位置创建与源目录相同的空文件夹结构 | |
| 查找叶子目录 | 返回不包含任何子目录的最底层目录(叶子目录)列表 | |
| 文件操作 | 复制指定格式文件 | 将源目录(及子目录)中所有指定格式的文件复制到目标文件夹 |
| 复制目录和文件 | 先复制目录结构,再将指定格式的文件复制到对应目录 | |
| 复制并重命名文件 | 将文件复制到目标文件夹,并按新名称保存(保留原扩展名) |
- 使用技巧与说明:
路径对象与字符串:获取路径列表的方法返回的是pathlib.Path对象列表,在进行字符串操作(如判断是否包含特定字符)时,常需要使用str(item)转换。若最终需要字符串路径,可以这样处理:[str(path) for path in path_list]。过滤逻辑:logical参数提供了灵活的筛选方式。例如,查找包含"报告"或"总结"的文件夹,可使用逻辑或;而查找同时包含"2024"和"月度报告"的文件夹,则需使用逻辑与。递归搜索:使用rglob('*')的方法会遍历指定路径下的所有子目录,适合需要对整个目录树进行操作的场景。
6.2、工具类 demo
下面是一个完整的 FileIO 类,封装了常见的文件路径操作,同时对3.1罗列的场景进行了简单的示例:
import shutil
import time
from pathlib import Path
from typing import List
class FileIO:
"""
使用 pathlib 封装常见文件路径操作的实用类
该类提供了一系列用于文件和目录操作的方法,包括遍历、筛选、清空文件夹等功能。
所有路径操作均基于 pathlib 库,确保跨平台兼容性。
"""
def __init__(self, source_folder: None | str | Path, target_folder: None | str | Path) -> None:
"""
初始化 FileIo 实例
Args:
source_folder: 源文件路径,可以是 字符串 或 Path对象
target_folder: 目标文件路径,可以是 字符串 或 Path对象
"""
self.source_folder = Path(source_folder) # 保证路径是Path 类型
self.target_folder = Path(target_folder) # 目标路径
if not self.source_folder.exists():
raise FileNotFoundError(f"源文件夹不存在: {self.source_folder}")
# 如果目标文件夹不存在则创建
if not self.target_folder.exists():
self.target_folder.mkdir(parents=True, exist_ok=True)
print(f"已创建目标文件夹: {self.target_folder}")
def list_folder_names(self, recursive: bool = True) -> List[str]:
"""
获取文件夹名称列表
Args:
recursive : 是否递归获取所有子文件夹,默认为 True
True - 递归获取所有子文件夹
False - 只获取直接子文件夹
Returns:
文件夹名称列表
"""
folder_path = self.source_folder
# 1、 第一种写法
folder_names = []
# 递归获取所有子文件夹名称
if recursive:
for item in folder_path.rglob("*"):
if item.is_dir():
folder_names.append(item.name)
else:
for item in folder_path.iterdir():
if item.is_dir():
folder_names.append(item.name)
# 2、 第二种写法(列表推导式)
# iterdir()比glob('*')更高效,
folder_names =[item.name
for item in (folder_path.rglob('*') if recursive else folder_path.iterdir()) if item.is_dir()]
return folder_names
def list_folder_paths(self, recursive: bool = True) -> List[Path]:
"""
获取文件夹路径列表
Args:
recursive : 是否递归获取所有子文件夹路径
Returns:
Path 对象列表,包含所有匹配的文件夹路径
"""
folder_path = self.source_folder
folder_paths = [item
for item in (folder_path.rglob('*') if recursive else folder_path.iterdir()) if item.is_dir()]
return folder_paths
def list_file_names(self, recursive: bool = True, include_extension: bool = True) -> List[str]:
"""
获取文件名称列表
Args:
recursive : 是否递归获取所有文件
include_extension : 是否包含文件扩展名
True - 包含扩展名 (e.g., "document.txt")
False - 不包含扩展名 (e.g., "document")
Returns:
文件名称列表
"""
file_path = self.source_folder
file_names = [
item.name if include_extension else item.stem
for item in (file_path.rglob('*') if recursive else file_path.iterdir())
if item.is_file()
]
return file_names
def list_file_paths(self, recursive: bool = True) -> List[Path]:
"""
获取文件路径列表
Args:
recursive : 是否递归获取所有子文件路径
Returns:
Path 对象列表,包含所有匹配的文件路径
"""
file_path = self.source_folder
file_paths = [item
for item in (file_path.rglob('*') if recursive else file_path.iterdir())
if item.is_file()]
return file_paths
@staticmethod
def filter_by_strings(items: List[str] | List[Path], target_strings: List[str], logical_or: bool = True) -> List[str]:
"""
根据指定的 字符串列表 筛选项目(文件、目录)
Args:
items : 要筛选的项目列表
target_strings : 目标字符串列表,用于筛选条件
logical_or : 逻辑操作类型
True - 逻辑或(包含任意一个目标字符串即匹配)
False - 逻辑与(包含所有目标字符串才匹配)
Returns:
筛选后的项目列表
"""
if logical_or: # 逻辑OR:包含任意一个字符串即可
# any(['.doc' in 'zkc\add.docx', '.py' in 'zkc\add.docx']) 有一个target_str包含在item中,则any为True,该item保留
filtered_items = [item
for item in items
if any(target_str in str(item) for target_str in target_strings)
]
else: # 逻辑AND:必须同时包含所有字符串
# all(['.doc' in 'zkc\add.docx', '.py' in 'zkc\add.docx'])
# 每个target_str必须都包含在同一个item中,有任意一个target_str不在item中,则all(target_str in str(item)为 False,该item排除
# filtered_items = []
# for item in items:
# if all(target_str in str(item) for target_str in target_strings):
# # print(target_str, str(item), target_str in str(item))
# filtered_items.append(item)
filtered_items = [item
for item in items
if all(target_str in str(item) for target_str in target_strings)
]
return filtered_items
@staticmethod
def clear_folder(target_dir: str|Path, max_attempts: int = 3, delay_seconds: float = 3.0) -> bool|None:
"""
通过删除并重建文件夹的方式来清空目标文件夹,支持充实机制
Args:
target_dir : 要删除的目标文件夹
max_attempts : 最大尝试次数,默认为 3 次
delay_seconds : 每次重试前的等待时间(秒),默认为 3 秒
Returns:
bool : 成功清空返回True,失败返回False
Raises:
PermissionError: 当文件被占用且无法删除时
OSError: 当发生其他操作系统错误时
"""
curr_attempt = 0
while curr_attempt < max_attempts:
try:
# 尝试清空文件夹的核心逻辑
target_path = Path(target_dir)
if target_path.exists():
shutil.rmtree(target_path) # 递归删除整个文件夹(包括子文件夹和文件)
time.sleep(0.05) # 短暂延迟确保删除完全生效
target_path.mkdir(parents=True, exist_ok=True) # 重新创建空文件夹
print(f"已成功清空文件夹: {target_dir}")
return True
except PermissionError as error:
# 捕获权限错误(通常是因为文件被占用)
curr_attempt += 1
print(f"尝试 {curr_attempt}/{max_attempts} 失败:文件可能正被其他程序占用。错误信息: {error}")
if curr_attempt < max_attempts:
print(f"等待 {delay_seconds} 秒后重试...")
time.sleep(delay_seconds)
else:
print(f"已达到最大重试次数 {max_attempts},清空文件夹失败。")
return False
except OSError as error:
# 捕获其他操作系统错误,例如路径无效等
print(f"发生操作系统错误: {error}")
return False
return None
def copy_directory_structure(self, recursive: bool = True):
"""
复制源目录结构到目标位置(不复制文件内容)
递归复制源目录下的所有子目录结构到目标位置,但不会复制任何文件内容
Args:
recursive : 是否递归复制所有子文件路径
"""
source_path = self.source_folder
target_path = self.target_folder
# 确保目标路径存在
target_path.mkdir(parents=True,exist_ok=True)
# 使用 rglob 递归遍历源目录下的所有子目录
for dir_path in source_path.rglob('*') if recursive else source_path.glob('*'):
if dir_path.is_dir():
# 计算当前目录相对于源目录的路径
try:
relative_path = dir_path.relative_to(source_path)
# print(f"{source_path}==相对路径=={relative_path}")
except ValueError:
# 如果 dir_path 不是 source_path 的子路径,跳过
continue
# 构建目标目录路径并创建
target_subdir = target_path / relative_path
target_subdir.mkdir(parents=True, exist_ok=True)
print(f"已创建目录: {target_subdir}")
def find_leaf_directories(self) -> List[Path]:
"""
查找并返回所有叶子目录(不包含子目录的目录)
Returns:
叶子目录的 Path 对象列表
"""
source_path = self.source_folder
leaf_directories = []
# 识别叶子目录:没有子目录的目录就是叶子目录
for dir_path in source_path.rglob('*'):
if dir_path.is_dir():
# 判断当前文件夹里有没有任意子文件夹,如果有子文件夹,则返回True,则不是叶子目录。
has_subdirectories = any(item.is_dir() for item in dir_path.iterdir())
if not has_subdirectories:
leaf_directories.append(dir_path)
# 输出所有叶子目录信息
result_paths = []
print("\n所有叶子目录(最深层次的子目录):")
for leaf_dir in leaf_directories:
try:
# 计算相对于源目录的路径用于显示
relative_leaf_path = leaf_dir.relative_to(source_path)
result_paths.append(source_path / relative_leaf_path)
# 计算深度
depth = len(relative_leaf_path.parts)
print(f"- {relative_leaf_path} (深度: {depth})")
except ValueError:
# 如果路径计算出错,跳过
continue
return result_paths
def copy_files(self, file_extension=".txt"):
"""
将一个文件夹里的所有指定格式文件复制到另一个目标文件夹
Args:
file_extension : 指定的文件后缀
"""
source_files = self.list_file_paths(True) #获取原始文件夹里所有的文件路径
# print(source_files)
for source_file in source_files:
if file_extension in str(source_file):
shutil.copy2(source_file, self.target_folder) #将原始文件夹里所有的文件复制到对应文件夹
print(f"已复制: {source_file} -> {self.target_folder}")
#将一个文件夹里的所有目录和指定格式文件复制到另一个文件夹
def copy_folders_and_files(self, file_extension='.tif') -> None:
self.copy_directory_structure(True)
source_files = self.list_file_paths(True) # 获取原始文件夹里所有的文件路径
for source_file in source_files:
if file_extension in str(source_file):
# 计算 source_file 相对于 self.source_folder 的相对路径
relative_path = source_file.relative_to(self.source_folder)
# 将相对路径拼接到目标文件夹下
target_file = self.target_folder / relative_path
shutil.copy2(source_file, target_file) # 将原始文件夹里所有的文件复制到对应文件夹
print(f"已复制: {source_file} -> {target_file}")
#将一个文件复制到目标文件夹里,并重命名
@staticmethod
def copy_rename_file(source_file_path:str|Path, target_folder:str|Path,new_filename:str) -> None:
extension_name = Path(source_file_path).suffix
target_file_path = Path(target_folder) / Path(new_filename +extension_name)
shutil.copy2(source_file_path, target_file_path)
print(f"已复制: {source_file_path} -> {target_file_path}")
if __name__ == '__main__':
source_folder = Path("zkc")
targe_folder = Path("output")
file_io = FileIO(source_folder, targe_folder)
# 测试筛选功能
target_strings = [".txt", "test"]
# 测试直接子文件夹相关方法
print("=== 直接子文件夹 ===")
current_folder_names = file_io.list_folder_names(recursive=False) #获取直接文件夹名
current_folder_paths = file_io.list_folder_paths(recursive=False) #获取直接文件夹路径
filtered_current_folder_paths_and = file_io.filter_by_strings(current_folder_paths, target_strings, logical_or=False) #按照逻辑与筛选含所有关键字的直接子文件夹路径
filtered_current_folder_paths_or = file_io.filter_by_strings(current_folder_paths, target_strings, True) #按照逻辑或筛选含任一关键字的直接子文件夹路径
print("直接子文件夹名称列表:", current_folder_names)
print("直接子文件夹路径列表:", current_folder_paths)
print("筛选后的直接子文件夹路径(AND):", filtered_current_folder_paths_and)
print("筛选后的直接子文件夹路径(OR):", filtered_current_folder_paths_or)
# 测试所有子文件夹相关方法
print("\n=== 所有子文件夹 ===")
all_folder_names = file_io.list_folder_names(True) # 获取所有子文件夹名
all_folder_paths = file_io.list_folder_paths(True) # 获取所有子文件夹路径
filtered_all_folder_paths_and = file_io.filter_by_strings(all_folder_paths, target_strings, logical_or=False) # 按照逻辑与筛选含所有关键字的所有子文件夹路径
filtered_all_folder_paths_or = file_io.filter_by_strings(all_folder_paths, target_strings, logical_or=True) # 按照逻辑或筛选含任一关键字的所有子文件夹路径
print("所有子文件夹名称列表:", all_folder_names)
print("所有子文件夹路径列表:", all_folder_paths)
print("筛选后的所有子文件夹路径(AND):", filtered_all_folder_paths_and)
print("筛选后的所有子文件夹路径(OR):", filtered_all_folder_paths_or)
# 测试直接子文件相关方法
print("\n=== 直接子文件 ===")
current_file_lists_with_extension = file_io.list_file_names(False, True) # 获取所有直接文件的名称,有扩展名
current_file_lists_without_extension = file_io.list_file_names(False, False) # 获取所有直接文件的名称,无扩展名
current_file_paths = file_io.list_file_paths(False) # 获取所有直接文件的路径
filtered_current_file_paths_and = file_io.filter_by_strings(current_file_paths, target_strings, logical_or=False) # 按照逻辑与筛选含所有关键字的直接子文件路径
filtered_current_file_paths_or = file_io.filter_by_strings(current_file_paths, target_strings, logical_or=True) # 按照逻辑或筛选含任一关键字的直接子文件路径
print("直接子文件名称列表(含扩展名):", current_file_lists_with_extension)
print("直接子文件名称列表(不含扩展名):", current_file_lists_without_extension)
print("直接子文件路径列表:", current_file_paths)
print("筛选后的直接子文件路径(AND):", filtered_current_file_paths_and)
print("筛选后的直接子文件路径(OR):", filtered_current_file_paths_or)
# 测试所有子文件相关方法
print("\n=== 所有子文件 ===")
all_file_lists_with_extension = file_io.list_file_names(True, True) # 获取所有文件的名称,有扩展名
all_file_lists_without_extension = file_io.list_file_names(True, False) # 获取所有文件的名称,无扩展名
all_file_paths = file_io.list_file_paths(True) # 获取所有文件的路径
filtered_all_file_paths_and = file_io.filter_by_strings(all_file_paths, target_strings, logical_or=False) # 按照逻辑与筛选含所有关键字的所有子文件路径
filtered_all_file_paths_or = file_io.filter_by_strings(all_file_paths, target_strings, logical_or=True) # 按照逻辑或筛选含任一关键字的所有子文件路径
print("所有子文件名称列表(含扩展名):", all_file_lists_with_extension)
print("所有子文件名称列表(不含扩展名):", all_file_lists_without_extension)
print("所有子文件路径列表:", all_file_paths)
print("筛选后的所有子文件路径(AND):", filtered_all_file_paths_and)
print("筛选后的所有子文件路径(OR):", filtered_all_file_paths_or)
# 清空目标文件夹里的所有内容
file_io.clear_folder(file_io.target_folder)
# 复制所有目录
file_io.copy_directory_structure(True) # True,复制所有目录,False,复制当前目录
# 找到所有叶子目录
all_leaves = file_io.find_leaf_directories()
print(all_leaves)
# 复制特定格式的文件到指定目录
file_io.copy_files(".docx")
# 清空目标文件夹里的所有内容
file_io.clear_folder(file_io.target_folder)
七、总结
pathlib 库提供了一种现代化、面向对象的方法来处理文件系统路径,比传统的 os.path 模块更直观和强大。通过 Path 对象,我们可以用更简洁的语法完成复杂的路径操作,同时自动处理不同操作系统的路径差异。
7.1、要点回顾
本文从 pathlib 的设计思想出发,先厘清 PurePath 与 Path 两条继承链的职责边界,再系统梳理了路径拼接、属性拆分、判断与操作方法,以及目录创建删除、移动重命名、iterdir/glob/rglob/walk 遍历匹配和文件读写、元信息获取等常用能力,最后通过批量改后缀、清理大日志、归档脚本与 FileIO 工具类等案例,把零散 API 串成可直接复用的实践方案。
7.2、实践建议
- 新代码统一用
Path替代os.path:路径拼接一律用/运算符,取文件名、后缀、父目录用name/suffix/parent,避免手写字符串切割与斜杠兼容判断。 - 遍历优先选对方法:只看当前层用
iterdir(),按模式筛选用glob(),需要递归用rglob(),要目录树结构用walk();注意它们返回生成器,多次使用先转list()。 - 危险操作先判断再执行:删除、覆盖前用
exists()/is_dir()校验,mkdir带上parents=True, exist_ok=True,跨分区移动用replace()或shutil.move(),非空目录删除交给shutil.rmtree()。
本文系统讲解Python 3.4+引入的pathlib模块,涵盖PurePath与Path类体系、路径对象创建、拼接、属性拆分、存在性判断、目录/文件的创建删除、遍历匹配(glob/rglob/match/walk)、读写操作及元信息获取;对比os模块,通过批量改后缀、日志清理、非空目录删除、日期归档等实战案例,展示其面向对象、跨平台、可读性强的核心优势。
1445

被折叠的 条评论
为什么被折叠?



