How to create new folder?
Categories:
Creating Directories in Python: A Comprehensive Guide to os.mkdir()
and os.makedirs()

Learn how to create single or multiple directories in Python using the os
module, handling common errors and best practices for robust file system operations.
Working with file systems is a fundamental aspect of many Python applications. Whether you're organizing data, setting up project structures, or managing temporary files, the ability to create new directories (folders) is essential. Python's built-in os
module provides powerful and flexible functions for this purpose: os.mkdir()
and os.makedirs()
.
Understanding os.mkdir()
: Creating a Single Directory
The os.mkdir()
function is used to create a single directory. It's straightforward but has a crucial limitation: it can only create the last component of the path provided. This means all parent directories in the path must already exist. If any intermediate directory does not exist, os.mkdir()
will raise a FileNotFoundError
.
import os
# Example 1: Creating a simple directory
directory_name = "my_new_folder"
try:
os.mkdir(directory_name)
print(f"Directory '{directory_name}' created successfully.")
except FileExistsError:
print(f"Directory '{directory_name}' already exists.")
except Exception as e:
print(f"An error occurred: {e}")
# Example 2: Attempting to create a nested directory with mkdir (will fail if 'parent_folder' doesn't exist)
# This will raise FileNotFoundError if 'parent_folder' does not exist
nested_directory_name = "parent_folder/child_folder"
try:
os.mkdir(nested_directory_name)
print(f"Directory '{nested_directory_name}' created successfully.")
except FileExistsError:
print(f"Directory '{nested_directory_name}' already exists.")
except FileNotFoundError:
print(f"Error: Parent directory for '{nested_directory_name}' does not exist. Use os.makedirs() instead.")
except Exception as e:
print(f"An error occurred: {e}")
Using os.mkdir()
to create a single directory and handling common errors.
try-except
blocks to gracefully handle potential errors like FileExistsError
or FileNotFoundError
. This makes your scripts more robust.Understanding os.makedirs()
: Creating Nested Directories
For creating directories where some or all of the parent directories in the path might not exist, os.makedirs()
is the function you need. It works recursively, creating all necessary intermediate directories to ensure the full path exists. This makes it incredibly convenient for setting up complex directory structures.
import os
# Example 1: Creating a nested directory structure
nested_path = "project_data/raw_files/2023"
try:
os.makedirs(nested_path)
print(f"Directory structure '{nested_path}' created successfully.")
except FileExistsError:
print(f"Directory structure '{nested_path}' already exists.")
except Exception as e:
print(f"An error occurred: {e}")
# Example 2: Using 'exist_ok=True' (Python 3.2+)
# This prevents FileExistsError if the directory already exists
another_path = "logs/daily_reports"
try:
os.makedirs(another_path, exist_ok=True)
print(f"Directory structure '{another_path}' ensured to exist.")
except Exception as e:
print(f"An error occurred: {e}")
Using os.makedirs()
to create nested directories and the exist_ok
parameter.
exist_ok=True
parameter (available since Python 3.2) is a highly recommended feature for os.makedirs()
. When set to True
, it prevents a FileExistsError
from being raised if the target directory already exists, making your code cleaner and more resilient.When to Use Which Function
Choosing between os.mkdir()
and os.makedirs()
depends on your specific needs and the expected state of the file system. Here's a simple decision flow:
flowchart TD A[Start] A --> B{Does parent directory exist?} B -->|Yes| C{Need to create only one directory?} C -->|Yes| D[Use os.mkdir()] C -->|No| E[Use os.makedirs()] B -->|No| E[Use os.makedirs()] D --> F[End] E --> F[End]
Decision flow for choosing between os.mkdir()
and os.makedirs()
.
Best Practices for Directory Creation
To ensure your directory creation logic is robust and maintainable, consider these best practices:
1. Use os.makedirs()
with exist_ok=True
by default
Unless you have a specific reason to raise an error if a directory already exists, os.makedirs(path, exist_ok=True)
is generally the safest and most convenient option. It ensures the directory path exists without failing if it's already there.
2. Handle permissions
Both os.mkdir()
and os.makedirs()
accept an optional mode
argument to set directory permissions (e.g., 0o755
). Be mindful of security and access control when setting permissions, especially in multi-user environments.
3. Use pathlib
for modern path manipulation
While os
module functions are powerful, Python's pathlib
module offers an object-oriented approach to file system paths, often leading to more readable and intuitive code. Path.mkdir()
is the pathlib
equivalent, supporting parents=True
and exist_ok=True
.
from pathlib import Path
# Using pathlib to create a directory
path_obj = Path("pathlib_example/data/temp")
try:
path_obj.mkdir(parents=True, exist_ok=True)
print(f"Directory structure '{path_obj}' created/ensured using pathlib.")
except Exception as e:
print(f"An error occurred with pathlib: {e}")
Creating directories using the pathlib
module.