轉自: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) 比對字尾,将檔案路徑中的空字元串" ",轉化為"\\ "