1

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.

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, very close, in the "Archive": "For_deposition", line the Archive value is used, but I want the For_deposition to be used. So, the value should be used not the key, unless the key is an instance of a dict as you have implemented.
@SpatialDigger at least I got close! updated the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.