本文最后更新于 2024-09-30T00:15:13+08:00
Path 创建
Path对象可以由一个path_str创建而来
1 2 3
| from pathlib import Path dir = Path("lfw")
|
Path 的拼接
不同于os.join来对子文件夹进行凭借,Path对象可以方便的使用/
符号将Path和str之间拼接起来
1 2
| file = "a.img" file_path = dir / file
|
Path 文件的walk
不同于os.walk对文件递归遍历,Path对象使用path.glob("正则表达表达式
")对子文件夹搜索。
- path.glob(dir)
对dir下的文件和目录进行搜索,不递归
- path.rglob(dir)对dir下的文件和目录搜索,递归搜索
1 2 3 4 5 6
| cwd.iterdir()
path_generate = path.rglob("*.jpg")
path_list = list(path_generate)
|
Path 对象的部分访问
上级目录
1 2 3 4 5 6 7 8 9 10
| image_file.parent
image_file.parents ''' [PosixPath('/home/bexgboost/downloads'), PosixPath('/home/bexgboost'), PosixPath('/home'), PosixPath('/')],list '''
|
文件名,后缀, 无后缀
1 2 3 4 5 6 7
| image_file.name
image_file.suffix
image_file.stem
|
Path对象是否存在
1 2 3
| entry.is_dir() entry.is_file() entry.exists()
|