Welcome, guest | Sign In | My Account | Store | Cart
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

Diff to Previous Revision

--- revision 1 2011-09-26 23:37:08
+++ revision 2 2011-09-26 23:38:24
@@ -5,7 +5,7 @@
     Creates a nested dictionary that represents the folder structure of rootdir
     """
     dir = {}
-    rootdir = rootdir.rstrip('/')
+    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)

History