Skip to main content
 首页 » 编程设计

python之限制os.walk遍历的嵌套目录数

2024年11月01日11softidea

我正在使用 Python 解析通过 wget 下载的 WordPress 网站。所有 HTML 文件都嵌套在一个复杂的文件夹结构中(感谢 WordPress 及其长 URL),例如 site_dump/2010/03/11/post-title/index.html。

但是,在 post-title 目录中还有其他目录用于 feed 和 Google News-esque 基于数字的索引:

site_dump/2010/03/11/post-title/index.html  # I want this 
site_dump/2010/03/11/post-title/feed/index.html  # Not these 
site_dump/2010/03/11/post-title/115232/site.com/2010/03/11/post-title/index.html 

我只想访问位于第 5 个嵌套级别 (site_dump/2010/03/11/post-title/index.html) 的 index.html 文件,而不是超出此级别。现在,我在 os.walk 循环中用斜杠 (/) 拆分 root 变量,并且只处理文件内部的文件5 级文件夹:

import os 
 
for root, dirs, files in os.walk('site_dump'): 
  nested_levels = root.split('/') 
  if len(nested_levels) == 5: 
    print(nested_levels)  # Eventually do stuff with the file here 

但是,这似乎有点低效,因为 os.walk 仍在遍历那些非常深的文件夹。有没有办法限制遍历目录树时 os.walk 的深度?

请您参考如下方法:

您可以就地修改 dirs 以防止进一步遍历目录结构。

for root, dirs, files in os.walk('site_dump'): 
  nested_levels = root.split('/') 
  if len(nested_levels) == 5: 
    del dirs[:] 
    # Eventually do stuff with the file here 

del dirs[:] 将删除列表的内容,而不是将 dirs 替换为对新列表的引用。执行此操作时,就地修改列表很重要。

来自docs ,topdown 指的是您省略的 os.walk 的可选参数,默认为 True:

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.