转自:https://mp.weixin.qq.com/s/FFXh8gRci4hMo6_gnBMPUg
工作中,有时会产生查找某一类文件的需求,比如log文件。或者在做图像类深度学习时,需要读取大类文件夹下,所有小类文件夹下的图片。专门为这个需求写一个函数太耽误时间。所以,今天分享一个我工作中遇到的第三方库imutils,并分享一下我对源码的理解。
from imutils import paths
# 要在哪条路径下查找
path = '...'
# 查找图片,得到图片路径
imagePaths = list(imutils.paths.list_images(basePath=path))
# 所有py文件,得到py文件路径
imagePaths = list(imutils.paths.list_files(basePath=path,,validExts=('.py')))
# 源码解读
def list_files(basePath, validExts=(".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff"), contains=None):
# loop over the directory structure
for (rootDir, dirNames, filenames) in os.walk(basePath):
# loop over the filenames in the current directory
for filename in filenames:
# if the contains string is not none and the filename does not contain
# the supplied string, then ignore the file
if contains is not None and filename.find(contains) == -1:
continue
# determine the file extension of the current file
ext = filename[filename.rfind("."):].lower()
# check to see if the file is an image and should be processed
if ext.endswith(validExts):
# construct the path to the image and yield it
imagePath = os.path.join(rootDir, filename).replace(" ", "\\ ")
yield imagePath
参数contains表示找到给定路径下,给定后缀文件类型,文件名中包含contains提供字段的文件
rfind() 返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1
ext = filename[filename.rfind("."):].lower() 将文件后缀转换成小写
ext.endswith(validExts) 匹配后缀,将文件路径中的空字符串" ",转化为"\\ "
转自:https://mp.weixin.qq.com/s/FFXh8gRci4hMo6_gnBMPUg