查找某文件夹下所有子文件夹内的py文件-3 一行代码搞定

转自: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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值