简体   繁体   中英

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

I have an API I'm accessing, which has a deep folder structure. I don't know the depth of the folder structure(definitely more than 4 levels and each folder has a different depth) but I want to get all folder, subfolder names and put them in a dict. As each folder has a name and id and I only can access the folder with the id, but need to match the name to make it usable. I'm still far from being an experienced coder so I hope someone can help me with this. As I came across this issue multiple times with different APIs. How should I for-loop when I don't know how many levels of subfolders there are?

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)

Output (with a mockup "root" dir containing subfolders):

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

It is super slow "around 40seconds" but it's the first solution that worked. I hope you guys can help me to solve this puzzle with faster code. I used a recursive function.

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM