imutils.path

 1 from imutils import paths 
 2 
 3 # 要在哪条路径下查找
 4 
 5 path = '...'
 6 
 7 # 查找图片,得到图片路径
 8 
 9 imagePaths = list(imutils.paths.list_images(basePath=path))
10 
11 # 所有py文件,得到py文件路径
12 
13 imagePaths = list(imutils.paths.list_files(basePath=path,,validExts=('.py')))
14 
15  

 

源码

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) 匹配后缀,将文件路径中的空字符串" ",转化为"\\ "

 

posted @ 2019-05-18 17:09  Pent°  阅读(941)  评论(0编辑  收藏  举报