获取目录的整个目录结构作为列表

Get the entire directory structure of a directory as list

所以我正在制作一个 GUI,它需要一个包含预配置目录的目录结构的列表。格式可以是这样的:

{"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"
      ]
    }
  [
}

格式不必完全像那样,但是是否有内置函数,也许在 os 模块中可以做到这一点?

可能是这样的递归?

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))