如何获取os.makedirs递归创建的所有新目录?
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
- Traverse Upward: Starting from your target path, we check each parent directory until we find one that already exists.
- Collect Missing Directories: We add every non-existent directory to a list as we go.
- 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). - 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_okparameter matchesos.makedirs()behavior: set it toTrueto 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

