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.
不能以任何通用方式反转生成器。唯一的解决方案是将它转换成一个序列,然后以相反的顺序在序列上迭代。在计算出早期的项之前,不一定知道生成器的后期项。
下面的解决方案使用反向。如果目录结构不深入,性能应该很好。
您需要了解,实际上可以修改由
os.walk
使用的dirs
。 (至少除非您显式地设置topdown=False
)。特别是,您可以删除目录,或者使用列表。
实际上应该不需要额外的费用就能做到。
首先,^{} 没有指定目录返回的顺序,因此如果我是您,我就不会依赖字母顺序。
话虽如此,您可以通过将^{} 设置为其默认值(
True
),然后将dirs
排序到位来选择遍历子目录的顺序:这将使
os.walk()
按名称的相反字典顺序遍历子目录。documentation解释了这是如何工作的:
相关问题 更多 >
编程相关推荐