Table of Contents
ToggleCreating directories programmatically is a common and essential task in many Python applications — from organizing output files and saving logs to preparing environments for data storage or project deployment.
In Python, the process of making a directory (or multiple directories) is made simple and efficient using the built-in os
module, particularly the os.makedirs()
function.
This function not only allows you to create a single directory but also automatically creates any necessary intermediate-level folders along the specified path.
It mirrors the functionality of the mkdir -p
command in Unix-like systems, making it ideal for scripting and automation.
What makes os.makedirs()
especially powerful is its flexibility: with optional parameters like exist_ok
, you can control whether it raises an error if the directory already exists, and with mode
, you can specify custom file permissions upon creation.
Overall, Python’s directory creation tools are robust and developer-friendly, helping streamline file system operations with minimal code and maximum control — a core part of writing efficient, reliable Python scripts for both simple and large-scale projects.
What is os.makedirs()
in Python?
Python’s os.makedirs()
is a function in the os
module that allows you to create a directory — and any necessary parent directories — in one go.
Think of it like mkdir -p
in Unix/Linux.
This is especially useful when you’re working with nested folder structures and want to avoid checking if each level exists manually.
os.makedirs(name, mode=0o777, exist_ok=False)
name
: The directory path you want to create.mode
(optional): The permission mode (defaults to0o777
).exist_ok
(optional): If set toTrue
, it won’t raise an error if the directory already exists.
Basic Example: Creating a Single Directory
import os
os.makedirs("my_new_folder")
This will create a folder named my_new_folder
in the current working directory.
Creating Nested Directories
import os
os.makedirs("projects/2025/python/scripts")
This will create all missing folders in the path:projects → 2025 → python → scripts
You don’t have to manually check or create each one. Python handles that for you.
Handling Existing Directories with exist_ok=True
If you run os.makedirs()
for a directory that already exists, Python will throw a FileExistsError
by default. To avoid this:
import os
os.makedirs("projects/2025/python/scripts", exist_ok=True)
This way, the script won’t break if the directory already exists.
Setting Directory Permissions
You can define permissions using the mode
parameter.
import os
os.makedirs("secure_folder", mode=0o755, exist_ok=True)
0o755
allows the owner to read/write/execute, and others to read/execute.Make sure you understand Linux/Unix file permission octals before using custom modes.
Real-World Use Case: Saving Logs
import os
from datetime import datetime
log_dir = f"logs/{datetime.now().strftime('%Y/%m/%d')}"
os.makedirs(log_dir, exist_ok=True)
with open(f"{log_dir}/log.txt", "w") as f:
f.write("This is a sample log entry.")
This script creates a dated folder structure and writes a log file. Useful for daily logging in production systems.
Best Practices
✅ Do | ❌ Avoid |
---|---|
Use exist_ok=True in most cases | Manually checking if the path exists |
Log or handle exceptions | Assuming directories always create successfully |
Keep paths OS-independent with os.path.join() | Hardcoding paths like "C:/path/..." |
Troubleshooting Common Errors
Error | Reason | Solution |
---|---|---|
FileExistsError | Directory already exists | Set exist_ok=True |
PermissionError | No write permission in the target location | Run script with proper permissions |
OSError: [Errno 2] | Part of the path is invalid | Double-check the full directory path |
Conclusion
Using os.makedirs()
in Python is a reliable and efficient way to work with file systems. Whether you’re building a data pipeline, setting up log folders, or organizing assets in a project, this function can simplify your workflow significantly.
It’s just one example of how Python’s standard library can help automate common tasks without the need for external dependencies.
Bonus: Use pathlib
for Modern Path Handling
from pathlib import Path
Path("projects/2025/python/scripts").mkdir(parents=True, exist_ok=True)
pathlib
is a more modern, object-oriented alternative to os
.
TL;DR
os.makedirs()
creates nested directoriesUse
exist_ok=True
to avoid errorsCombine with
datetime
,os.path.join()
, orpathlib
for best results
Have Questions?
Drop a comment below or reach out via our contact page if you’re building a project and want help with directory structures, file handling, or automation scripts in Python.
People also ask
What is the difference between mkdir and makedirs?
The key difference lies in how deeply they create directories:
os.mkdir(path)
creates a single directory. If any part of the path (like parent folders) doesn’t exist, it raises an error.os.makedirs(path)
creates the entire directory tree, including all necessary parent folders. It’s like doingmkdir -p
in Unix.
What does the os mkdir() function do in Python?
The os.mkdir()
function in Python is used to create a single directory at the specified path. It requires that the parent directory already exists; otherwise, it will raise a FileNotFoundError
.
📌 Syntax:
os.mkdir("new_folder")
What is the os function in Python?
os
is not a function, but a built-in module in Python that provides a way to interact with the operating system. It lets your Python programs:
Work with file systems (create, rename, delete files and folders)
Access environment variables
Handle paths
Perform OS-level tasks (e.g., running system commands)
📌 Example uses:
import os
os.name # Returns the name of the OS ('posix', 'nt', etc.)
os.getcwd() # Gets current working directory
os.listdir() # Lists files in a directory
Stay ahead of the curve with the latest insights, tips, and trends in AI, technology, and innovation.