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

如何获取os.makedirs递归创建的所有新目录?

How to Log Directories Created by os.makedirs()

Great question! The built-in os.makedirs() doesn’t include a native way to report exactly which directories it created recursively, but we can build a simple wrapper function to track and print these new directories. Here’s how to do it:

Solution 1: Using pathlib (Modern, Cross-Platform)

pathlib makes path handling cleaner and more intuitive across operating systems. This function will traverse up from your target path to find the first existing parent directory, collect all missing directories along the way, then create them and log the results:

import os
from pathlib import Path

def makedirs_with_log(target_path, exist_ok=False):
    target = Path(target_path)
    dirs_to_create = []
    
    # Traverse upward from the target to find existing parent directories
    current_dir = target
    while not current_dir.exists():
        dirs_to_create.append(current_dir)
        current_dir = current_dir.parent
        # Stop if we reach the root directory (avoids infinite loop)
        if current_dir == current_dir.parent:
            break
    
    # Reverse to get directories in creation order (shallow to deep)
    dirs_to_create.reverse()
    
    # Create the full directory tree
    os.makedirs(target_path, exist_ok=exist_ok)
    
    # Print all newly created directories
    if dirs_to_create:
        print("Newly created directories:")
        for dir_path in dirs_to_create:
            print(f"- {dir_path}")
    else:
        print("No new directories were created (path already exists).")
    
    return dirs_to_create

Solution 2: Using os.path (Legacy/Compatible Approach)

If you prefer using the older os.path module instead of pathlib, here’s an equivalent version:

import os

def makedirs_with_log(target_path, exist_ok=False):
    dirs_to_create = []
    current_path = target_path
    
    # Traverse upward to find existing parent directories
    while not os.path.exists(current_path):
        dirs_to_create.append(current_path)
        current_path = os.path.dirname(current_path)
        # Stop at the root directory
        if current_path == os.path.dirname(current_path):
            break
    
    # Reverse to get correct creation order
    dirs_to_create.reverse()
    
    # Create the directory tree
    os.makedirs(target_path, exist_ok=exist_ok)
    
    # Log results
    if dirs_to_create:
        print("Newly created directories:")
        for dir_path in dirs_to_create:
            print(f"- {dir_path}")
    else:
        print("No new directories were created (path already exists).")
    
    return dirs_to_create

How It Works

  1. Traverse Upward: Starting from your target path, we check each parent directory until we find one that already exists.
  2. Collect Missing Directories: We add every non-existent directory to a list as we go.
  3. Reverse the List: This ensures we have directories in the order they need to be created (from shallowest to deepest, though os.makedirs() handles recursion automatically).
  4. Create and Log: After creating the full tree with os.makedirs(), we print all directories that were missing (and thus created).

Example Usage

If /tmp/path/to/desired/directory already exists, calling:

makedirs_with_log("/tmp/path/to/desired/directory/a/b/c")

Will output:

Newly created directories:
- /tmp/path/to/desired/directory/a
- /tmp/path/to/desired/directory/a/b
- /tmp/path/to/desired/directory/a/b/c

Notes

  • The exist_ok parameter matches os.makedirs() behavior: set it to True to avoid errors if the target path already exists (no directories will be logged in this case).
  • This approach assumes no concurrent processes are modifying the directory structure between the existence check and creation. For most single-threaded use cases, this is safe.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:04:43