pathlib库使用

一个较新的文件路径操作库,建议使用python3.6版本以上。部分属于翻译自官方文档的个人理解,不保证正确。

基本使用

一部分函数在进阶使用中会介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 导入库
from pathlib import Path
# 先实例化对象
file = Path("D://example")
# 列举子目录(文件夹)为列表
list_sub_dirs = [x for x in file.iterdir() if x.is_dir()]
# 根据正则匹配文件
list(file.glob('**/*.py'))
# 获取文件属性或方法
file.exists() # 文件是否存在
file.is_dir() # 是否为文件夹
file.is_file() # :)
file.drive # 返回盘符 "c:"
file.parent # 父文件夹
file.name # 返回文件或文件夹全名
PurePath.suffix # 返回后缀名
PurePath.suffixes # 返回后后缀名列表:) "/x.tar.gz" ==> ['.tar', '.gz']
PurePath.stem # 返回文件名(无后缀名)

进阶使用

pathglob

Path.glob(pattern, *, case_sensitive=None, recurse_symlinks=False)

根据pattern提供的正 则表达式匹配文件

1
2
3
4
5
6
7
8
9
10
sorted(Path('.').glob('*.py'))
# [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
sorted(Path('.').glob('*/*.py'))
# [PosixPath('docs/conf.py')]
sorted(Path('.').glob('**/*.py'))
#[PosixPath('build/lib/pathlib.py'),
# PosixPath('docs/conf.py'),
# PosixPath('pathlib.py'),
# PosixPath('setup.py'),
# PosixPath('test_pathlib.py')]