py:遍历指定目录

File : walk_dir.py (直接右键另存为下载)
Type : python
Brief : 遍历目录下所有指定类型的目录或文件


import os
import platform
import re

def NewWalk(top, suffixs, exdirs):
    """
    NotImplement new walk function with suffix and dir filter.
    """
    top = os.fspath(top)
    dirs = []
    nondirs = []

    # We have read permission to our project obviously.
    scandir_it = os.scandir(top)
    with scandir_it:
        while True:
            try:
                try:
                    entry = next(scandir_it)
                except StopIteration:
                    break
            except OSError as error:
                return

            try:
                is_dir = entry.is_dir()
            except OSError:
                # If is_dir() raises an OSError, consider that the entry is not
                # a directory, same behaviour than os.path.isdir().
                is_dir = False

            if is_dir:
                # 'entry is not is exdirs'
                if entry.name not in exdirs:
                    dirs.append(entry.name)
            else:
                # 'suffixs is empty' or 'entry is in suffix'
                if not suffixs or os.path.splitext(entry.name)[1] in suffixs:
                    nondirs.append(entry.name)

    yield top, dirs, nondirs

    # Recurse into sub-directories
    islink, join = os.path.islink, os.path.join
    for dirname in dirs:
        new_path = join(top, dirname)
        if not islink(new_path):
            yield from NewWalk(new_path, suffixs, exdirs)

def GetDirsRecursive(paths, suffixs=[], exdirs=[]):
    """
    Get dirs recursive with suffix and dir filter.
    """
    flags = []
    for path in paths:
        for root, dirs, files in NewWalk(path, suffixs, exdirs):
            # files or dirs is not empty
            if files or dirs:
                flags.append(root)
    return flags

LOC_DIR = os.path.dirname(os.path.abspath(__file__))

for item in (GetDirsRecursive(
                [os.path.join(LOC_DIR, ''),],
                ['.c', '.cpp', '.h', '.hpp' ],
                ['sample', ])):
    print(item)

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 [ yehuohan@gmail.com ]

文章标题:py:遍历指定目录

本文作者:Y

发布时间:2019-03-26, 19:53:30

最后更新:2019-10-02, 22:36:01

原始链接:http://yehuohan.github.io/2019/03/26/Gist/python/py-%E9%81%8D%E5%8E%86%E6%8C%87%E5%AE%9A%E7%9B%AE%E5%BD%95/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。