反方向的os.walk()?

2024-05-23 23:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行os.walk()时,我得到的结果是按字母数字顺序排列的;从0开始,到z结束。是否可以反转?

所以如果我有3个目录,apple/bananas/pears/,我希望返回pears/bananas/apples/

显然,我可以将所有dir存储为一个列表,然后.reverse(),但这需要很长时间。


Tags: 目录apple列表osdir字母数字reverse
3条回答

不能以任何通用方式反转生成器。唯一的解决方案是将它转换成一个序列,然后以相反的顺序在序列上迭代。在计算出早期的项之前,不一定知道生成器的后期项。

下面的解决方案使用反向。如果目录结构不深入,性能应该很好。

import os

directory = '/your/dir/'
for root, dirs, files in reversed(list(os.walk(directory))):
    print root, dirs, files

您需要了解,实际上可以修改由os.walk使用的dirs。 (至少除非您显式地设置topdown=False)。

特别是,您可以删除目录,或者使用列表。

import os
for root, dirs, files in os.walk(startdir):
    dirs.sort(reverse=True)
    # Also remove dirs you do not need!

实际上应该不需要额外的费用就能做到。

首先,^{}没有指定目录返回的顺序,因此如果我是您,我就不会依赖字母顺序。

话虽如此,您可以通过将^{}设置为其默认值(True),然后将dirs排序到位来选择遍历子目录的顺序:

import os
top='/home/aix'
for root, dirs, files in os.walk(top, topdown=True):
  print root
  dirs.sort(reverse=True)

这将使os.walk()按名称的相反字典顺序遍历子目录。

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; 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.

相关问题 更多 >