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

问题描述 投票:0回答:2

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

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)))
python dictionary for-loop subdirectory
2个回答
1
投票
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

0
投票

这是超级慢的“大约40秒”,但这是第一个有效的解决方案。我希望你们能帮助我用更快的代码解决这个难题。我使用了递归函数。

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']
© www.soinside.com 2019 - 2024. All rights reserved.