如何遍历 Python 中列表中的列表,不知道目录深度?

How iterate through lists in lists in Python, unknows dir depth?

我有一个 API 我正在访问,它有一个很深的文件夹结构。我不知道文件夹结构的深度(肯定超过 4 个级别,每个文件夹都有不同的深度)但我想获取所有文件夹、子文件夹名称并将它们放在字典中。由于每个文件夹都有一个名称和 ID,我只能访问具有该 ID 的文件夹,但需要匹配名称才能使用。 我离成为一名经验丰富的编码员还很远,所以我希望有人能帮助我解决这个问题。当我用不同的 API 多次遇到这个问题时。 不知道有多少级子文件夹,如何for-loop?

folder_ids = []
folder_names = []
folders_dict = {}

response_list = client.get_asset_children(assetid) # Get subfolder and files from asset with API
assets = response_list.results

for item in assets:
    folder_ids.append(item['id'])
    folder_names.append(item['name'])

folder_dict.update(dict(zip(folder_names, folder_ids)))
from pathlib import Path

path = Path("root")

for item in path.glob("**"):
    if item.is_dir():
        print(item)

输出(带有包含子文件夹的模型 "root" 目录):

root
root\a
root\a\deeper
root\a\deeper\even deeeeeper
root\b
root\c
root\c\foo

它超级慢 "around 40seconds" 但它是第一个有效的解决方案。我希望你们能帮助我用更快的代码解决这个难题。 我使用了递归函数。

def get_subassets(assetid): # Version 004
    """List Assets"""
    response_list = client.get_asset_children(assetid)
    assets = response_list.results

    global assets_dict  # Create a global variable for assets dictionary
    assets_dict = {}  # Create the empty assets dictionary

    for item in assets:
        if item['type'] == 'folder':
            all_folders.append(item['name'])
            get_subassets(item['id'])
            # print("It's a folder: ", item['name'])
        if item['type'] == 'file':
            all_files.append(item['name'])
            # print("It's a file:   ", item['name']