我正在编写一个下降到目录树的脚本(使用 os.walk()),然后访问与某个文件扩展名匹配的每个文件。但是,由于我的工具将用于的某些目录树还包含子目录,而这些子目录又包含 LOT 无用(出于此脚本的目的)的东西,我想我会添加用户指定要从遍历中排除的目录列表的选项。
这很容易使用 os.walk()。毕竟,由我决定是否真的要访问由 os.walk() 产生的相应文件/目录,或者只是跳过它们。问题是,例如,如果我有这样的目录树:
root--
|
--- dirA
|
--- dirB
|
--- uselessStuff --
|
--- moreJunk
|
--- yetMoreJunk
我想排除 uselessStuff 及其所有子目录,os.walk() 仍将下降到 uselessStuff 的所有(可能数千个)子目录中,其中,不用说,它减慢了很多。在一个理想的世界里,我可以告诉 os.walk() 甚至不要费心产生更多 uselessStuff 的 child ,但据我所知,没有办法做到这一点(是吗?)。
有人有想法吗?也许有一个第三方库可以提供类似的东西?
最佳答案
修改 dirs
in-place 将修剪 os.walk
访问的(后续)文件和目录:
# exclude = set(['New folder', 'Windows', 'Desktop'])
for root, dirs, files in os.walk(top, topdown=True):
dirs[:] = [d for d in dirs if d not in exclude]
来自帮助(os.walk):
When topdown is true, the caller can modify the dirnames list in-place (e.g., via 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...
https://stackoverflow.com/questions/19859840/