一、说明
pathlib 是在Python3上使用的强悍路径管理库,以简洁的方式管理各种操作系统中使用的路径。
二、安装
pip install pathlib
三、主要用法
from pathlib import *
path=Path()
Path.iterdir() # 遍历目录的子目录或者文件
Path.is_dir() # 判断是否是目录
Path.glob() # 过滤目录(返回生成器)
list(Path().glob('*.py')) # 通配符匹配
list(Path().glob('*.py'))[0] # 获取某一通配符匹配后的文件
Path.resolve() # 返回绝对路径
Path.exists() # 判断路径是否存在
Path.open() # 打开文件(支持with)
Path.unlink() # 删除文件或目录(目录非空触发异常)
Path.chmod() # 更改路径权限, 类似os.chmod()
Path.expanduser() # 展开~返回完整路径对象
Path.mkdir() # 创建目录
Path.rename() # 重命名路径
Path.rglob() # 递归遍历所有子目录的文件
Path.parts # 分割路径 类似os.path.split(), 不过返回元组
path.suffix # 文件后缀
path.stem # 文件名不带后缀
path.name # 带后缀的完整文件名
path.parent # 路径的上级目录
path.chmod(0o444) # 更改路径权限 chmod(mode)
四、延展用法
from pathlib import *
# 获取当前路径
path = Path().cwd()
print(path)
path = Path(path)
# 返回路径字符串中所包含的各部分
print(path.parts)
# 返回路径字符串中的驱动器盘符
print(path.drive)
# 返回路径字符串中的根路径
print(path.root)
# 返回路径字符串中的盘符和根路径
print(path.anchor)
# 返回当前路径的全部父路径
print(path.parents)
# 返回当前路径的上一级路径
print(path.parent)
print(path.parents[0]) # 获取某一父路径
# 返回当前路径中的文件名
print(path.name)
# 返回当前路径中的文件所有后缀名
print(Path(path, 'app.py').suffixes)
# 返回当前路径中的文件后缀名
print(Path(path, 'app.py').suffix)
print(Path(path, 'app.py').suffixes[0]) # 获取某一文件后缀
# 返回当前路径中的主文件名
print(path.stem)
# 将当前路径转换成 UNIX 风格的路径
print(path.as_posix())
# 将当前路径转换成 URL。只有绝对路径才能转换,否则将会引发 ValueError
print(path.as_uri())
# 判断当前路径是否为绝对路径
print(path.is_absolute())
# 将多个路径连接在一起,作用类似于前面介绍的斜杠(/)连接符
print(path.joinpath('aa', 'bb', 'cc'))
print(Path(path, 'aa', 'bb', 'cc')) # 以上等效方法
# 判断当前路径是否匹配指定通配符
print(Path(path, 'app.py').match('*.py'))
# 将当前路径中的文件名替换成新文件名,非真实替换
print(path.with_name('ss'))
# 将当前路径中的文件后缀名替换成新的后缀名。如果当前路径中没有后缀名,则会添加新的后缀名
print(path.with_suffix('.py'))
# 获取当前文件和文件夹的元信息
print(path.stat())
# 文件大小
print(path.stat().st_size)
# 文件时间
print(path.stat().st_atime)
五、PurePath 类的用法
PurePath 类(以及 PurePosixPath 类和 PureWindowsPath 类)都提供了大量的构造方法、实例方法以及类实例属性,供我们使用。
- PurePath类构造方法
需要注意的是,在使用 PurePath 类时,考虑到操作系统的不同,如果在 UNIX 或 Mac OS X 系统上使用 PurePath 创建对象,该类的构造方法实际返回的是 PurePosixPath 对象;反之,如果在 Windows 系统上使用 PurePath 创建对象,该类的构造方法返回的是 PureWindowsPath 对象。
- 在 Windows 系统上执行
from pathlib import *
# 创建PurePath,实际上使用PureWindowsPath
path = PurePath('my_file.txt')
print(type(path))
- 执行结果
<class 'pathlib.PureWindowsPath'>
- 不同系统大小写
from pathlib import *
# Unix风格的路径区分大小写
print(PurePosixPath('C://my_file.txt') == PurePosixPath('c://my_file.txt'))
# Windows风格的路径不区分大小写
print(PureWindowsPath('C://my_file.txt') == PureWindowsPath('c://my_file.txt'))
九、参考文档
https://www.jianshu.com/p/84f31a23aca7
https://www.cnblogs.com/wagyuze/p/11578139.html