传入一个根目录,遍历所有文件或者需要的后缀文件

以下代码是 imutils的paths库中的,我这里只是搬运来,一点讲解下。

这个人讲解 yield 蛮好的:https://blog.csdn.net/mieleizhi0522/article/details/82142856/

from imutils import paths

# -*- coding: utf-8 -*-

import os


image_types = (".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff")


def list_images(basePath, contains=None):
    # return the set of files that are valid
    return list_files(basePath, validExts=image_types, contains=contains)

# 带yield的函数是一个生成器
def list_files(basePath, validExts=None, 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 validExts is None or ext.endswith(validExts):
                # construct the path to the image and yield it
                imagePath = os.path.join(rootDir, filename)
                yield imagePath #因为有yield,所以每次运行到这就返回,然后这个方法用list包裹,所以就自动迭代了。


tmp_list = [1,2,3]
def find_tmp():
    for num in tmp_list:
        yield num
        print('num')

if __name__ == '__main__':
    file_root = r''

    # 因为list_files包含yield,所以一般当作函数用,不启作用,可以把有yield的函数看做return,之后再把它看做一个是生成器(generator)的一部分
    # (带yield的函数才是真正的迭代器),所以,当用list包裹有yield的函数时,就会自动迭代了。
    tmp = list(list_files(file_root))
    print(tmp)
    #
    # g = find_tmp()
    # print(next(g))
    # print('find')
    t = list(find_tmp())
    print(t)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值