使用Generator和Recursion遍历目录

在遍历或搜索文件系统时,如果目录的文件很多,目录结果复杂,可能会消耗较多的内存来保存已遍历的信息,所以使用Generator就是一个比较好的选择。另外,使用Recursion会降低代码量,使代码可读性更强。

遍历目录,返回所有的文件和目录

def scan_dir_gen(dir_path):
    """Scan directory recursively and yield all files and directories.

    Args:
        dir_path: Path object to be scanned.
    """
    if dir_path is None or not isinstance(dir_path, Path):
        raise TypeError('dir_path must be a Path object')

    # The current directory.
    yield dir_path
    for path in dir_path.iterdir():
        if path.is_dir():
            # Recursively tranverse the directory.
            yield from scan_dir_gen(path)
        else:
            yield path

遍历目录,只返回只有文件的目录

def dir_only_has_files_gen(dir_path):
    """Scan the directory recursively and returns directories which contain only files.

    Args:
        dir_path: Path object to be scanned.
    """
    if dir_path is None or not isinstance(dir_path, Path):
        raise TypeError('dir_path must be a Path object')

    has_dir = False
    for path in dir_path.iterdir():
        if path.is_dir():
            has_dir = True
            yield from dir_only_has_files_gen(path)
    if not has_dir:
        yield dir_path
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,486评论 25 709
  • 在此处先列下本篇文章的主要内容 简介 next方法的参数 for...of循环 Generator.prototy...
    醉生夢死阅读 5,281评论 3 8
  • 简介 基本概念 Generator函数是ES6提供的一种异步编程解决方案,语法行为与传统函数完全不同。本章详细介绍...
    呼呼哥阅读 4,733评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,174评论 19 139
  • 梭罗总是那么喜爱自然。在梭罗的《远行》里,有这么一段文字是关于苹果的命名的,我觉得很有意思。 1836年,伦敦园艺...
    梨子不青阅读 5,045评论 0 1

友情链接更多精彩内容