Home > Net >  Get the entire directory structure of a directory as list
Get the entire directory structure of a directory as list

Time:01-20

So I'm making a GUI which needs a list containing the directory structure of a preconfigured directory. The format could go something like this:

{"base_folder":
  [
    "file1.txt",
    "file2.txt",
    {"directory1":
      [
        "nested_image.png",
        {"nested_directory":
          [
            "deep_video.mp4",
            "notes.txt"
          ]
        },
        "another_image.png",
        "not_a_file_type.thisisafile"
      ]
    },
    "game.exe",
    "mac_port_of_game.app",    # yeah I know that a .app is a bundle but can't be bothered
                               # to make the entire bundle structure
    "linux_port_of_game.elf",
    {"coding_stuff":
      [
        "code.py",
        "morecode.c"
      ]
    }
  [
}

The format doesn't have to be exactly like that, but is there a built in function, maybe in the os module that can do this?

CodePudding user response:

Probably something like this with a recurse?

from pathlib import Path
import json

def get_files(root, tree):
    subtree = {root.name: []}
    files = list(root.glob('*'))

    for file in files:
        if file.is_file():
            subtree[root.name].append(file.name)
        else:
            subtree[root.name].append(get_files(file, tree))
    return subtree

root = Path(r'/Users/user/Desktop')
tree = get_files(root,[])
print(json.dumps(tree, indent=4, sort_keys=True))
  •  Tags:  
  • Related