如何在 os walk Python 2.7 中跳过目录

How to skip directories in os walk Python 2.7

我写了一个图像雕刻脚本来辅助我的工作。该工具按指定扩展名雕刻图像并与哈希数据库进行比较。

该工具用于搜索已安装的驱动器,其中一些驱动器上装有操作系统。

我遇到的问题是,当使用 OS 挂载驱动器时,它会在 'All Users' 目录中搜索,因此会包括我本地磁盘中的图像。

我不知道如何跳过 'All Users' 目录并坚持安装的驱动器。

我的 os.walk 部分如下:

for path, subdirs, files in os.walk(root):
    for name in files:
        if re.match(pattern, name.lower()):
                appendfile.write (os.path.join(path, name))
                appendfile.write ('\n')
                log(name)
                i=i+1

非常感谢任何帮助

假设 All Users 是目录的名称,您可以从 subdirs 列表中删除该目录,这样 os.walk() 就不会重复访问它。

例子-

for path, subdirs, files in os.walk(root):
    if 'All Users' in subdirs:
        subdirs.remove('All Users')
    for name in files:
        if re.match(pattern, name.lower()):
                appendfile.write (os.path.join(path, name))
                appendfile.write ('\n')
                log(name)
                i=i+1

如果您只想在特定 parent 内 不行走 All Users,您也可以在上面 if条件。

os.walk documentation-

os.walk(top, topdown=True, onerror=None, followlinks=False)

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False is ineffective, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

topdown 通常为真,除非另有说明。

如果您有多个目录要删除,您可以在 oder 中使用切片分配来删除 subdirs

中排除的目录
excl_dirs = {'All Users', 'some other dir'}

for path, dirnames, files in os.walk(root):
    dirnames[:] = [d for d in dirnames if d not in excl_dirs]
    ...

the documentation 所述:

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; ..