【问题标题】:Traverse directories recursively and return a nested list with the subdirectories and files in Python递归遍历目录并返回一个嵌套列表,其中包含 Python 中的子目录和文件
【发布时间】:2020-08-16 23:25:36
【问题描述】:

我想在 Python 中递归遍历一个目录并获取所有子目录和文件的嵌套列表。 我已经找到了几十个解决方案来解决第一部分(递归遍历目录),但是没有一个允许我以我需要的格式获得输出。

对于使用哪些库没有限制/偏好。我尝试使用 pathlib,但 os.walk() 也很好。此外,它必须是一个递归函数。循环就好了。

我有以下结构:

root
├── file1.txt
├── file2.txt
├── sub1
│   ├── subfile1.txt
│   └── subsub
│       └── subsubfile1.txt
└── sub2

我需要结果是这样的嵌套列表:

[
  {
    'name': 'file1.txt'
  },
  {
    'name': 'file2.txt'
  },
  {
    'name': 'sub1',
    'children': [
      {
        'name': 'subfile1.txt'
      },
      {
        'name': 'subsub',
        'children': [
          {
            'name': 'subsubfile1.txt'
          }
        ]
      }
    ]
  },
  {
    'name': 'sub2'.
    'children': []
  }
]

这是我已经走了多远,但它没有给出正确的结果:

from pathlib import Path
def walk(path: Path, result: list) -> list:
    for p in path.iterdir():
        if p.is_file():
            result.append({
                'name': p.name
            })
            yield result
        else:
            result.append({
                'name': p.name,
                'children': list(walk(p, result))
            })
walk(Path('root'), [])  # initial call

除了这段代码不起作用之外,我还遇到了递归集合的问题。当我尝试漂亮地打印它时,它显示:

'children': [ <Recursion on list with id=4598812496>,
                    <Recursion on list with id=4598812496>],
      'name': 'sub1'},

是否可以将该 Recursion 对象作为列表获取?

如果有人想知道为什么我需要这种结构而不是像 pathlib.glob() 返回的那种扁平列表,那是因为这个列表将被我 API 另一端的这段代码使用: https://vuetifyjs.com/en/components/treeview/#slots

【问题讨论】:

    标签: python recursion treeview pathlib


    【解决方案1】:

    你可以在递归中使用os.listdir

    import os
    def to_tree(s=os.getcwd()):
      return [{'name':i} if os.path.isfile(f'{s}/{i}') else 
                  {'name':i, 'children':to_tree(f'{s}/{i}')} for i in os.listdir(s)]
    

    在与您的示例类似的文件结构上运行上述函数时,结果是:

    import json
    print(json.dumps(to_tree(), indent=4))
    

    输出:

    [
      {
        "name": "file1.txt"
      },
      {
        "name": "file2.txt"
      },
      {
        "name": "sub1",
        "children": [
            {
                "name": "subfile1.txt"
            },
            {
                "name": "subsub",
                "children": [
                    {
                        "name": "subsubfile1.txt"
                    }
                ]
             }
          ]
      },
      {
        "name": "sub2",
        "children": []
      }
    ]
    

    【讨论】:

    • 很好,这似乎可以满足我的需求。短而优雅。谢谢。
    猜你喜欢
    • 2011-12-24
    • 1970-01-01
    • 2013-03-04
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    相关资源
    最近更新 更多