pathlib 中的 Path类

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("正则表达表达式")对子文件夹搜索。

  1. path.glob(dir) 对dir下的文件和目录进行搜索,不递归
  2. path.rglob(dir)对dir下的文件和目录搜索,递归搜索
1
2
3
4
5
6
cwd.iterdir()
# 是一个迭代器
path_generate = path.rglob("*.jpg")
# path_generate是一个generate对象,只能用next(),或者for循环提取
path_list = list(path_generate)
# path_list 是一个list

Path 对象的部分访问

上级目录

1
2
3
4
5
6
7
8
9
10
image_file.parent
# Path('/home/bexgboost/downloads')
image_file.parents
'''
[PosixPath('/home/bexgboost/downloads'),
PosixPath('/home/bexgboost'),
PosixPath('/home'),
PosixPath('/')],list
'''

文件名,后缀, 无后缀

1
2
3
4
5
6
7
image_file.name
#'midjourney.png'
image_file.suffix
#'.png'
image_file.stem
#'midjourney'

Path对象是否存在

1
2
3
entry.is_dir()
entry.is_file()
entry.exists()

pathlib 中的 Path类
https://jfsas.github.io/2024/09/23/pathlib-中的-Path类/
作者
JFSAS
发布于
2024年9月23日
许可协议