Python – Recursive subfolder loop

Question:

I’m looking to build a dictionary based on a directory’s subfolders. Note that this isn’t an OS directory, so I can’t use the os library. The below code works, but is limited to 3 levels of subdirectories. How can I build a loop that will handle any number of subdirectories?

 if isinstance(parentfolder, Folder):
    for child in parentfolder.child:
        subchildren = []
        if isinstance(child, Folder):
           for subchild in child.child: 
              if isinstance(subchild, Folder):
                 subchildren.append({'folder' : subchild})
           children.append({'folder' : subchildren})
    DirDict.append({'folder' : parentfolder, 'children': children })

The desired outcome is a dictionary that looks something like the following, while the child folder meets the "isinstance" condition :

{'folder' : 'somefolder', 'children' : { 'folder' : 'somechildfolder', 'children' : { 'folder' : 'somegrandchildfolder' [,...] } } }   
Asked By: user2953714

||

Answers:

Something roughly like

def walk(dir):
  return {
    'folder': dir,
    'children': [walk(c) for c in dir.child if isinstance(c, Folder)]
  }
Answered By: Gene