You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python从字典(含嵌套字典)创建目录?

Creating Directories from Flat and Nested Dictionaries in Python

Got it, let's walk through how to turn both simple flat dictionaries and nested dictionaries into actual directory structures using Python. This is super handy when you need to programmatically set up a folder hierarchy for projects, data storage, or anything else that needs organized directories.

1. Flat Dictionary (Simple Directory List)

First, let's cover the basic case: a flat dictionary where keys represent the directory paths you want to create (the values can be anything, since we're just using the keys here).

Example Implementation

We'll use os.makedirs (or pathlib for a more modern approach) to create directories. The exist_ok=True flag ensures we don't get errors if the directory already exists.

Using os Module

import os

# Flat dict: keys are directory paths, values are irrelevant here
flat_directory_map = {
    "data/raw": None,
    "processed/reports": None,
    "assets/icons": None,
    "logs/daily": None
}

for dir_path in flat_directory_map.keys():
    # Create the directory (and parent folders if needed)
    os.makedirs(dir_path, exist_ok=True)

Using pathlib (Modern Approach)

pathlib makes path handling more intuitive with object-oriented syntax:

from pathlib import Path

# You could even use a set here since values don't matter, but dict works too
flat_dirs = {"data/raw", "processed/reports", "assets/icons", "logs/daily"}

for dir_path in flat_dirs:
    Path(dir_path).mkdir(parents=True, exist_ok=True)

Key Notes

  • parents=True (in pathlib) or the default behavior of os.makedirs will create any missing parent directories (e.g., if data/ doesn't exist, it will be created along with data/raw).
  • exist_ok=True prevents FileExistsError if the directory already exists—perfect for running scripts multiple times without issues.

2. Nested Dictionary (Hierarchical Directories)

For nested dictionaries, where each key is a directory and its value is another dictionary representing subdirectories, we need a recursive approach to traverse each level of the hierarchy.

Example Implementation

Let's say we have a nested dict that mirrors the folder structure we want:

nested_directory_map = {
    "projects": {
        "python": {
            "automation_scripts": None,
            "data_analysis_notebooks": None
        },
        "web_dev": {
            "frontend": {
                "components": None,
                "styles": None
            },
            "backend": {
                "api_routes": None,
                "database": None
            }
        }
    },
    "documentation": {
        "user_guides": None,
        "api_reference": None
    }
}

Recursive Function with os Module

import os

def create_nested_directories(base_path, dir_hierarchy):
    for dir_name, sub_hierarchy in dir_hierarchy.items():
        # Build the full path for the current directory
        current_dir = os.path.join(base_path, dir_name)
        # Create the directory
        os.makedirs(current_dir, exist_ok=True)
        # If there are subdirectories, recursively call the function
        if sub_hierarchy is not None:
            create_nested_directories(current_dir, sub_hierarchy)

# Start creating from the current working directory (".")
create_nested_directories(".", nested_directory_map)

Recursive Function with pathlib

Again, pathlib simplifies path operations:

from pathlib import Path

def create_nested_dirs_pathlib(base_path, dir_hierarchy):
    base_dir = Path(base_path)
    for dir_name, sub_hierarchy in dir_hierarchy.items():
        current_dir = base_dir / dir_name
        current_dir.mkdir(parents=True, exist_ok=True)
        # Recurse if there are subdirectories
        if sub_hierarchy is not None:
            create_nested_dirs_pathlib(current_dir, sub_hierarchy)

create_nested_dirs_pathlib(".", nested_directory_map)

How It Works

  • The function starts at the base path, then iterates over each key-value pair in the dictionary.
  • For each key, it creates the directory at the current path.
  • If the value is another dictionary (not None), it calls itself with the new directory path and the sub-dictionary, continuing the process until all levels are created.

Edge Cases to Consider

  • If you're working with older Python versions (pre-3.2), os.makedirs doesn't have exist_ok=True. You can use a try-except block instead:
    try:
        os.makedirs(dir_path)
    except OSError:
        # Directory already exists, skip
        pass
    
  • Make sure you have write permissions for the target location—otherwise you'll get a PermissionError.

内容的提问来源于stack exchange,提问作者Bhanuchander Udhayakumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:53:32