Script to Generate Directory Structure in JSON

This script recursively generates the directory structure of the current directory and outputs it in JSON format. It uses the os module to navigate directories.
 avatar
unknown
python
a year ago
590 B
3
Indexable
import os
import json

def get_structure(path):
    structure = {}
    for item in os.listdir(path):
        item_path = os.path.join(path, item)
        if os.path.isdir(item_path):
            structure[item] = get_structure(item_path)
        else:
            structure[item] = None
    return structure

# Get the current directory
current_dir = os.path.dirname(os.path.abspath(__file__))

# Get the structure
project_structure = {os.path.basename(current_dir): get_structure(current_dir)}

# Convert to JSON and print
print(json.dumps(project_structure, indent=2))
Editor is loading...
Leave a Comment