Skip to content

Instantly share code, notes, and snippets.

@UmerHA
Created October 31, 2023 00:38
Quickly get a flat or nested directory structure, and optionally save to yaml
import os
import yaml
from pprint import pprint
def dir_structure(dir_path, nested=False):
result = []
if nested:
# return directory structure as nested dict
for item in os.listdir(dir_path):
item_path = os.path.join(dir_path, item)
if os.path.isdir(item_path):
result.append({item: list_dir(item_path, nested=nested)})
else:
result.append(item)
else:
# return directory structure as flat file list
for root, _, files in os.walk(dir_path):
for file in files:
full_path = os.path.join(root, file)
result.append(full_path)
return result
flat_dir_structure = dir_structure('..')
nested_dir_structure = dir_structure('..', nested=True)
print(flat_dir_structure)
pprint(nested_dir_structure)
with open("directory_structure.yaml", "w") as f:
yaml.dump(nested_dir_structure, f, default_flow_style=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment