【问题标题】:How to change the order of os.walk() output?如何更改 os.walk() 输出的顺序?
【发布时间】:2021-01-20 23:56:37
【问题描述】:

因此,os.walk() 显然“垂直”移动目录,遍历输入的第一个目录及其所有子目录,然后移动到下一个“顶级”目录。

代码:

import os

os.chdir("/home/test")
inp = str(os.getcwd() + "/input")

l = list(os.walk(inp))

输出:

[('/home/test/input', ['a', 'b', 'c'], ['d.txt']),
 ('/home/test/input/a', ['aa'], ['ac.txt', 'ab.txt']),
 ('/home/test/input/a/aa', [], [], 83),
 ('/home/test/input/b', [], ['bb.txt', 'bc.txt', 'ba.txt']),
 ('/home/test/input/c', ['ca'], [], 81),
 ('/home/test/input/c/ca', ['caa'], ['cab.txt']),
 ('/home/test/input/c/ca/caa', [], ['caaa.txt'])]

有没有办法“水平”行走? 我希望输出看起来像这样:

[('/home/test/input', ['a', 'b', 'c'], ['d.txt']),
 ('/home/test/input/a', ['aa'], ['ac.txt', 'ab.txt']),
 ('/home/test/input/b', [], ['bb.txt', 'bc.txt', 'ba.txt']),
 ('/home/test/input/c', ['ca'], [], 81),
 ('/home/test/input/a/aa', [], [], 83),
 ('/home/test/input/c/ca', ['caa'], ['cab.txt']),
 ('/home/test/input/c/ca/caa', [], ['caaa.txt'])]

这样它就会在目录abc 中移动,然后再深入。

编辑:添加 topdown=False 参数没有帮助:

[('/home/philipp/test/input/a/aa', [], []),
 ('/home/philipp/test/input/a', ['aa'], ['ac.txt', 'ab.txt']),
 ('/home/philipp/test/input/b', [], ['bb.txt', 'bc.txt', 'ba.txt']),
 ('/home/philipp/test/input/c/ca/caa/x', [], []),
 ('/home/philipp/test/input/c/ca/caa', ['x'], ['caaa.txt']),
 ('/home/philipp/test/input/c/ca', ['caa'], ['cab.txt']),
 ('/home/philipp/test/input/c', ['ca'], []),
 ('/home/philipp/test/input', ['a', 'b', 'c'], ['d.txt'])]

之后我仍然可以使用循环对列表进行排序,但也许有一种更快、更优雅的方法来做到这一点。

(最终脚本中使用的文件和目录的数量可能会比上例中的多。)

【问题讨论】:

  • 常用术语是“深度优先”和“广度优先”。
  • 你看文档了吗?这不是topdown参数控制的吗?
  • @Barmar 不幸的是没有。这只是把这一切颠倒过来(见编辑过的帖子)。

标签: python list sorting os.walk python-os


【解决方案1】:

要回答您的问题,我认为没有办法使用一两行代码来做到这一点。不过,使用os 模块还有更长的方法可以做到这一点!你可以试试这个:

import os

def _dir_list(path):
    files = [os.path.join(path, f) for f in os.listdir(path)]
    print(str(files) + "\n")
    for f in files:
        if os.path.isdir(os.path.join(path, f)):
            _dir_list(os.path.join(path, f))

path = r"C:\PATH"

_dir_list(path)

基本上,这会获取 1 个目录中的所有文件夹,而无需深入研究它们。然后,它在文件中递增,并且对于每个文件,它再次执行该功能,获取那个目录中的文件,基本上做你想做的事情。

我们使用os.listdir()限制目录,它以列表的形式返回所有当前文件夹。

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 2011-10-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多