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

Python 限制os.walk遍历的嵌套目录数,python,html-parsing,os.walk,Python,Html Parsing,Os.walk,我正在使用Python解析通过wget下载的WordPress站点。所有HTML文件都嵌套在一个复杂的文件夹结构中(多亏了WordPress及其长URL),如site\u dump/2010/03/11/post title/index.HTML 但是,在post title目录中,还有其他用于提要和基于数字的谷歌新闻索引的目录: site_dump/2010/03/11/post-title/index.html # I want this site_dump/2010/03/11/post

我正在使用Python解析通过wget下载的WordPress站点。所有HTML文件都嵌套在一个复杂的文件夹结构中(多亏了WordPress及其长URL),如
site\u dump/2010/03/11/post title/index.HTML

但是,在
post title
目录中,还有其他用于提要和基于数字的谷歌新闻索引的目录:

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个嵌套级别的index.html文件(
site\u dump/2010/03/11/post title/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的深度?

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

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。执行此操作时,必须就地修改列表

从中,用
自上而下的
表示您省略的
os.walk
的可选参数,默认为
True

当topdown为True时,调用方可以就地修改dirnames列表 (可能使用del或slice赋值)和walk()只会递归 进入名称保留为dirnames的子目录;这可能是 用于删减搜索,强制执行特定的访问顺序,甚至 通知walk()调用方创建或重命名的目录 在它再次恢复walk()之前。自顶向下时修改目录名 False无效,因为在自底向上模式中 在生成dirpath本身之前生成dirname


令人惊叹的!这太完美了。谢谢