相关疑难解决方法(0)

过滤os.walk()目录和文件

我正在寻找一种方法来包含/排除文件模式并从os.walk()调用中排除目录.

这就是我现在正在做的事情:

import fnmatch
import os

includes = ['*.doc', '*.odt']
excludes = ['/home/paulo-freitas/Documents']

def _filter(paths):
    matches = []

    for path in paths:
        append = None

        for include in includes:
            if os.path.isdir(path):
                append = True
                break

            if fnmatch.fnmatch(path, include):
                append = True
                break

        for exclude in excludes:
            if os.path.isdir(path) and path == exclude:
                append = False
                break

            if fnmatch.fnmatch(path, exclude):
                append = False
                break

        if append:
            matches.append(path)

    return matches

for root, dirs, files in os.walk('/home/paulo-freitas'):
    dirs[:] = _filter(map(lambda d: …
Run Code Online (Sandbox Code Playgroud)

python filtering os.walk

41
推荐指数
3
解决办法
8万
查看次数

标签 统计

filtering ×1

os.walk ×1

python ×1