Welcome, guest | Sign In | My Account | Store | Cart

Creates a nested dictionary that represents a folder structure. Here is an example of what the resulting dictionary might look like:

{
    "root": {
        "folder2": {
            "item2": None, 
            "item1": None
        }, 
        "folder1": {
            "subfolder1": {
                "item2": None, 
                "item1": None
            }, 
            "subfolder2": {
                "item3": None
            }
        }
    }
}
Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import os

def get_directory_structure(rootdir):
    """
    Creates a nested dictionary that represents the folder structure of rootdir
    """
    dir = {}
    rootdir = rootdir.rstrip(os.sep)
    start = rootdir.rfind(os.sep) + 1
    for path, dirs, files in os.walk(rootdir):
        folders = path[start:].split(os.sep)
        subdir = dict.fromkeys(files)
        parent = reduce(dict.get, folders[:-1], dir)
        parent[folders[-1]] = subdir
    return dir

1 comment

Mike F 12 years, 6 months ago  # | flag

FINALLY. I've spent an hour or two now looking for a recipe like this and couldn't find a proper one (due to the ambiguity of the terms as I was trying to plug em into Google, I'd imagine). I've come across two or three recipes that weren't satisfactory and have spent a while trying to get one of them to work as I wanted, but this is exactly what I was going for. Phew. Thanks.

Created by Andrew Clark on Mon, 26 Sep 2011 (MIT)
Python recipes (4591)
Andrew Clark's recipes (1)

Required Modules

Other Information and Tasks