Advertisement
There’s something oddly satisfying about writing code that shapes the file system—making folders exactly where you need them. If you’ve done much Python work, you’ve probably come across the os module. It quietly handles system-level tasks like file management, and one of its simplest yet frequently used functions is os.mkdir().
At first glance, it just creates a folder. But a closer look shows there’s more to it—subtle behavior, edge cases, and a few things you should know to use it properly. This article breaks it down with real use cases and practical tips for clean and predictable directory creation.
The function os.mkdir() creates a single folder. You give it a path, and if everything checks out, a new directory appears. The simplest form looks like this:
import os
os.mkdir("new_folder")
This will create a folder called new_folder in the same directory where the script is running. But that’s the easy part. Behind the scenes, Python checks if a folder with that name already exists. If it does, it throws a FileExistsError. If the parent folder isn’t there, you get a FileNotFoundError.
There is also a second parameter, mode, which defines permissions (such as read/write access) using Unix-style flags. Most people skip it, and Python applies a default. A third parameter, dir_fd, is rarely used but allows creating a folder relative to an open file descriptor.
If you pass a relative path, the folder is created in the current working directory. For an absolute path, it places it exactly where you specify. What’s important to know is this function only creates one directory at a time. That’s a limitation that matters in more complex scripts.
One of the main things people get wrong with os.mkdir() is assuming it can create a whole directory path at once. If you try something like data/2025/June/logs and any folder in that chain doesn’t exist yet, the function fails. That’s because os.mkdir() only works if all parent folders are already there—it doesn’t handle deep folder creation automatically.
You'll need to create each folder step by step or use os.makedirs(), which handles the whole path without extra effort. But let’s say you still want to use os.mkdir()—you’ll need some checks in place to avoid runtime issues:
import os
folder_name = "logs"
try:
os.mkdir(folder_name)
print(f"Folder created: {folder_name}")
except FileExistsError:
print(f"Folder already exists: {folder_name}")
except PermissionError:
print(f"No permission to create folder: {folder_name}")
except OSError as e:
print(f"Error: {e}")
This is a safe pattern. It catches common problems and keeps your script running cleanly. One of the most common issues is PermissionError. If the script tries to write where it doesn’t have access—like system folders—it will fail. So make sure your script is running in a directory you fully own and control.
Top of Form
Bottom of Form
While os.mkdir() works for one folder, os.makedirs() handles a full directory path—even if none of the parent folders exist yet. This makes it more useful when setting up folders, such as reports/2025/June, in automated or dynamic projects that require structured file outputs.
import os
os.makedirs("reports/2025/June", exist_ok=True)
The exist_ok=True part avoids errors if the folder already exists. With os.mkdir(), you’d have to manually check each level or create folders one at a time using multiple lines of code.
So why would anyone still use os.mkdir()? It’s lighter, faster, and simpler. If you want to avoid accidentally creating parent folders or want strict control over folder creation, os.mkdir() keeps things clear. You know exactly what’s being made and where.
It's also useful when working with loops, where each new folder is created in sequence, and you want to handle each step explicitly. For broader or nested directory creation, though, os.makedirs() is often the better and more efficient fit.
In many scripts, especially ones that generate logs, reports, or images, you often need to make sure a certain folder exists before writing files into it. Here’s a typical pattern:
import os
output_dir = "output"
if not os.path.exists(output_dir):
os.mkdir(output_dir)
This avoids the error from trying to create a folder that already exists. But if your script runs in parallel with others or might create folders at the same time, this pattern can fail. Two processes might check, and then both try to create the folder, leading to a race condition.
It’s better to just try and create the folder and catch the error:
try:
os.mkdir("output")
except FileExistsError:
pass
This way, even if another process creates the folder first, your script still runs cleanly.
When writing portable scripts, always use os.path.join() to build paths. This handles differences between operating systems:
import os
path = os.path.join("output", "images")
os.mkdir(path)
It keeps your code compatible with both Windows and Unix-style systems. If you’re creating temporary folders during tests or for throwaway data, look into the tempfile module, which automatically handles cleanup and avoids naming conflicts.
In automation, os.mkdir() is often used to set up environments before a job runs. If the folder is already there, the job continues. If it’s missing, the script builds it. This makes processes predictable and reduces manual setup.
os.mkdir() might seem like a simple function, but it plays a useful role in organizing files and guiding how scripts work with the file system. It creates one directory—nothing more. This limited behavior is a strength when you want full control and know the structure ahead of time. For basic, clear folder creation, it does the job well without adding overhead. If your task involves multiple nested folders or cleanup steps, consider other tools like os.makedirs() or tempfile. But when you want predictable behavior and don’t mind handling the setup manually, os.mkdir() remains a reliable, no-nonsense choice in many day-to-day Python scripts.
Advertisement
Learn how to build an MCP server using only five lines of Python code. This guide walks you through a minimal setup using Python socket programming, ideal for lightweight communication tasks
How to use os.mkdir() in Python to create folders reliably. Understand its limitations, error handling, and how it differs from other directory creation methods
GenAI is proving valuable across industries, but real-world use cases still expose persistent technical and ethical challenges
AI agents aren't just following commands—they're making decisions, learning from outcomes, and changing how work gets done across industries. Here's what that means for the future
Multilingual LLM built with synthetic data to enhance AI language understanding and global communication
How 7 popular apps are integrating GPT-4 to deliver smarter features. Learn how GPT-4 integration works and what it means for the future of app technology
The Water Jug Problem is a classic test of logic and planning in AI. Learn how machines solve it, why it matters, and what it teaches about decision-making and search algorithms
See how Intelligent Process Automation helps businesses automate tasks, reduce errors, and enhance customer service.
Want to run AI models on your laptop without a GPU? GGML is a lightweight C library for efficient CPU inference with quantized models, enabling LLaMA, Mistral, and more to run on low-end devices
How Python Tuple Methods and Operations work with real code examples. This guide explains tuple behavior, syntax, and use cases for clean, effective Python programming
Can you get the best of both GANs and autoencoders? Adversarial Autoencoders combine structure and realism to compress, generate, and learn more effectively
Curious about GPT-5? Here’s what to know about the expected launch date, key improvements, and what the next GPT model might bring