簡體   English   中英

遞歸遍歷目錄並返回一個嵌套列表,其中包含 Python 中的子目錄和文件

[英]Traverse directories recursively and return a nested list with the subdirectories and files in Python

我想遞歸遍歷 Python 中的目錄並獲取所有子目錄和文件的嵌套列表。 我已經找到了幾十個解決方案來解決第一部分(遞歸遍歷目錄),但沒有一個允許我以我需要的格式獲得 output。

使用哪些庫沒有限制/偏好。 我嘗試使用 pathlib,但 os.walk() 也很好。 此外,它不必是遞歸 function。 一個循環就好了。

我有以下結構:

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'},

是否可以將遞歸 object 作為列表?

如果有人想知道為什么我需要這種結構而不是像 pathlib.glob() 返回的那種扁平列表,那是因為這個列表將被我的 API 另一側的代碼使用: https://vuetifyjs.com/ zh/components/treeview/#slots

您可以在遞歸中使用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)]

在與您的示例類似的文件結構上運行上面的 function 時,結果是:

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

Output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM