博客
关于我
python Path模块的使用 glob iglob name
阅读量:798 次
发布时间:2023-03-06

本文共 1880 字,大约阅读时间需要 6 分钟。

1、获取当前文件及父文件夹的路径

from pathlib import Path  FILE = Path(__file__).resolve()  print('文件路径:', FILE)  ROOT = FILE.parents[0]  # YOLOv5 的根目录  print('根目录:', ROOT)  # 另一种方法  print('当前工作目录:', Path.cwd())

执行结果:

文件路径:/Users/jjw/Desktop/后端项目/yolov5.6/my_test.py  根目录:/Users/jjw/Desktop/后端项目/yolov5.6  当前工作目录:/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  print(Path('./MaskDataSet/data.yaml').is_file())  # 判断文件是否存在  print(Path('./MaskDataSet').is_file())  # 只有路径但没有文件  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  # 获取当前文件下的 runs 文件夹下的所有文件夹  print(glob.iglob('./runs/*'))  for i in glob.iglob('./runs/*'):      print(i)  # 对获取到的文件夹进行排序  print(sorted(glob.iglob('./runs/*')))

执行结果:

./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

转载地址:http://cmafk.baihongyu.com/

你可能感兴趣的文章
Python Sphinx自动摘要:成员函数的自动列表
查看>>
Python SQL和NoSQL数据库操作实战
查看>>
python stdout flush_sys.stdout.flush()方法的用法
查看>>
python string 运算
查看>>
Python str与bytes之间的转换
查看>>
Python subprocess ffmpeg
查看>>
python subprocess Permission denied Errno 13
查看>>
Python subprocess.call - 将变量添加到 subprocess.call
查看>>
Python Subprocess.Popen 从一个线程
查看>>
Python subprocess.Popen 作为 Windows 上的不同用户
查看>>
Python转换PPT为PDF
查看>>
Python subprocess.Popen() 等待完成
查看>>
Python sum 二维列表中具有相同第一个值的元素
查看>>
Python Sympy模块NoConversion:收敛到根失败;请尝试n<;15或MaxSteps>;50
查看>>
Python sys.MODULES包含尚未导入的模块
查看>>
python sys模块使用
查看>>
Python tarfile、zipfile解压模块讲解
查看>>
python tcp server传输成功之后进行删除_python学习之路(三)使用socketserver进行ftp断点续传...
查看>>
python车牌识别系统+车辆管理+计费系统(图像识别)django框架 计算机毕业设计
查看>>
Python threading.Thread 只能使用私有方法 self.__Thread_stop() 停止
查看>>