Spatial Digger
Spatial Digger

Reputation: 1993

Creating a folder directory structure in python from a nested json listing

I have the following json file, it is read into python as a dictionary json.load(json_file)

{
    "directory_structure":
    {
        "version": 1.0,
        "folders":
        {
            "Documentation": "Documentation",
            "Archive": "For_deposition",
            "Model": "Model",
            "Orthomosaic": "Orthomosaic",
            "Project":
            {
                "Input_Data": "Input_Data"
            },
            "Tiles": "Tiles"
        }
}

What I would like to do is to use this to build the directory structure as given under the "folders" key. I tried the following:

    folders = directory_structure["folders"]
    for dir in folders:
        os.mkdir(dir)

But this gives me this where the Project and Input_Data folders will not be created:

Documentation
For_deposition
Model
Orthomosaic
{'Project': 'Project', 'Input_Data': 'Input_Data'}
Tiles

The folder structure I'm aiming for is, where the Input_Data folder is within the Project folder:

Documentation
For_deposition
Model
Orthomosaic
Project
-- Input_Data
Tiles

The json file can be changed if it is not optimal for this.

Upvotes: 1

Views: 597

Answers (1)

aloha_erich
aloha_erich

Reputation: 138

This code works for me.

import json
import os

def make_directory_structure(dic):
    for key in dic:
        if isinstance(dic[key], dict):
            os.mkdir(key)
            os.chdir(key)
            make_directory_structure(dic[key])
            os.chdir('..')
        else:
            os.mkdir(dic[key])

with open("structure.json" , "r") as f:
    data = json.load(f)

folders = data["directory_structure"]["folders"]

make_directory_structure(folders)

Upvotes: 1

Related Questions