1、获取当前文件及父文件夹的路径
from pathlib import Path
FILE = Path(__file__).resolve()
print('FILE\n', FILE)
ROOT = FILE.parents[0] # YOLOv5 root directory
print('root\n', ROOT)
# 另一种方法
print('Path.cwd()\n', Path.cwd())
执行结果:
FILE
/Users/jjw/Desktop/后端项目/yolov5.6/my_test.py
root
/Users/jjw/Desktop/后端项目/yolov5.6
Path.cwd()
/Users/jjw/Desktop/后端项目/yolov5.6
2、获取文件的后缀并用小写表示
from pathlib import Path
print(Path('jjw/hello/1.txt').suffix.lower())
print(Path('/jjw/hello/1.txt').suffix.lower())
print(Path('/jjw/hello/1.TXT').suffix)
执行结果:
.txt
.txt
.TXT
3、判断文件是否存在
from pathlib import Path
# 判断给定的文件是否存在 ./MaskDataSet/data.yaml 正确的路径所以打印True
print(Path('./MaskDataSet/data.yaml').is_file())
# 只有路径没有文件所以打印FALSE
print(Path('./MaskDataSet').is_file())
# 不存在的文件,所以打印FALSE
print(Path('./MaskDataSet/111.txt').is_file())
打印结果
True
False
False
4、glob获取文件夹并对其进行路径进行排序
import glob
# 获取当前文件下的runs文件夹下的所有文件夹 需要注意的是返回来的是乱序的
print(glob.glob('./runs/*'))
# 对获取到的文件夹进行排序
print(sorted(glob.glob('./runs/*')))
运行结果:
['./runs/exp0', './runs/exp1', './runs/exp6', './runs/exp3', './runs/exp4', './runs/exp5', './runs/exp2']
['./runs/exp0', './runs/exp1', './runs/exp2', './runs/exp3', './runs/exp4', './runs/exp5', './runs/exp6']
5、iglob 和glob相似,只不过前者返回的是一个迭代器对象,后者返回的是个列表
import glob
print ( glob. iglob( './runs/*' ) )
for i in glob. iglob( './runs/*' ) :
print ( i)
print ( sorted ( glob. iglob( './runs/*' ) ) )
执行结果:
<generator object _iglob at 0x112369f90>
./runs/exp9
./runs/exp7
./runs/exp0
./runs/exp1
./runs/exp6
./runs/exp8
./runs/exp10
./runs/exp11
./runs/exp3
./runs/exp4
./runs/exp5
./runs/exp2
['./runs/exp0', './runs/exp1', './runs/exp10', './runs/exp11', './runs/exp2', './runs/exp3', './runs/exp4', './runs/exp5', './runs/exp6', './runs/exp7', './runs/exp8', './runs/exp9']
‘Return an iterator which yields the paths matching a pathname pattern’ 源码解释:返回一个迭代器对象,这个对象返回的是匹配到的路径
6、name 属性
from pathlib import Path
print ( Path( "jjw/1.txt" ) . name)
输出结果;也就是显示文件名称(带后缀)
1.txt