In [1]: import os from pathlib import Path import glob
方法1
In [3]: dirpath="D:\\test\\1" #判断是否是目录 if os.path.isdir(dirpath): img_names=[] # 获取所有文件名 dir_names = os.listdir(dirpath) for img_name in dir_names: # 获取固定后缀文件名 if os.path.splitext(img_name)[1] == '.jpg': img_names.append(img_name) else: print("路径错误,请输入目录!") print("dir_names:",dir_names) print("img_names:",img_names) print("os.path.splitext(img_name):",os.path.splitext(img_names[0]))
dir_names: ['66734.jpg', '66734.txt', '66991.jpg', '66991.txt', '67046.jpg', '67046.txt', '68248.jpg', '68248.txt', '68351.jpg', '68351.txt', '68550.jpg', '68550.txt'] img_names: ['66734.jpg', '66991.jpg', '67046.jpg', '68248.jpg', '68351.jpg', '68550.jpg'] os.path.splitext(img_name): ('66734', '.jpg')
方法2
In [4]: # 获取所有文件路径 file_paths=glob.glob(dirpath) # 获取固定后缀文件路径 img_paths=glob.glob(dirpath+"\\*.jpg") print("file_paths:",file_paths) print("img_paths:",img_paths)
file_paths: ['D:\\test\\1'] img_paths: ['D:\\test\\1\\66734.jpg', 'D:\\test\\1\\66991.jpg', 'D:\\test\\1\\67046.jpg', 'D:\\test\\1\\68248.jpg', 'D:\\test\\1\\68351.jpg', 'D:\\test\\1\\68550.jpg']
方法3
In [5]: # 获取固定后缀文件路径 image_suffixes = (".jpeg", ".jpg", ".png", ".bmp") img_paths=[p for p in Path(dirpath).glob("**/*") if p.suffix.lower() in image_suffixes] print("img_paths:",img_paths) print("img_paths[0]:",img_paths[0])
img_paths: [WindowsPath('D:/test/1/66734.jpg'), WindowsPath('D:/test/1/66991.jpg'), WindowsPath('D:/test/1/67046.jpg'), WindowsPath('D:/test/1/68248.jpg'), WindowsPath('D:/test/1/68351.jpg'), WindowsPath('D:/test/1/68550.jpg')] img_paths[0]: D:\test\1\66734.jpg