creating a directory structure

Suppose we have a directory that contains the following folders

    a
        b
            c
                d
                e
                f
                    g
                    h
                    i

And we'd like to represent this as the dictionary: {'': {'a': {'b': {'c': {'e': {}, 'd': {}, 'f': {'i': {}, 'h': {}, 'g': {}}}}}}}

Then the following code snippet can be modified to your use case. It's use case is to create a directory structure like above while walking the filesystem in the html directory located outside of the directory that the script is in.

    
import os
import sys
from os import walk

script_directory = os.path.dirname(os.path.realpath(__file__))
os.chdir("../html")
html_directory = os.getcwd()

directory_structure = {}

for dir_path, dirs, file_names in walk(html_directory):
    for name in file_names:
        full_path = os.path.join(dir_path, name)
        is_html_file = name[-4:] == "html"
        if is_html_file:
            relative_path = os.path.relpath(full_path)

            sub_directory = directory_structure

            for sub_path in relative_path.split("\\"):
                sub_directory = sub_directory.setdefault(sub_path, {})

    

Note that we're taking full advantage of setdefault to create subdirectories, and refreshing the value of sub_directory to the latest dictionary. See setdefault for more information


comments section