How to create a directory in Python
Learn how to create a directory in Python. Explore various methods, tips, real-world applications, and common error debugging.

To create a directory in Python is a fundamental skill for developers. It's essential for file organization, project structures, and workflow automation, and Python’s built-in modules make this process simple.
In this article, you’ll find several techniques to create directories, complete with practical tips, real-world applications, and advice to help you debug common errors you might encounter.
Basic directory creation with os.mkdir()
import os
# Create a new directory
os.mkdir("new_directory")
print(f"Directory 'new_directory' created successfully")--OUTPUT--Directory 'new_directory' created successfully
The os module is Python's standard interface for operating system functions, and os.mkdir() is the most direct way to create a single directory. The function takes a path as an argument—in this case, a simple string—and creates a folder named "new_directory" in the current location.
Keep in mind that os.mkdir() is intentionally simple. It will raise an error if the directory already exists or if a parent directory in the specified path is missing. This makes it reliable for creating one folder at a time in an existing location.
Common directory creation techniques
While os.mkdir() is straightforward, Python offers more robust tools to handle nested directories or situations where a folder might already exist.
Using os.makedirs() for nested directories
import os
# Create nested directories in one go
os.makedirs("parent/child/grandchild", exist_ok=True)
print(f"Nested directories created successfully")--OUTPUT--Nested directories created successfully
When you need to create a directory structure with multiple levels, such as parent/child/grandchild, os.makedirs() is the perfect tool. It recursively builds every necessary folder in the path, saving you from creating each one manually. It’s a more powerful and convenient alternative to os.mkdir().
- The
exist_ok=Trueargument is a key feature. It tells Python not to raise an error if the directory already exists, which makes your scripts more robust and re-runnable.
Using pathlib.Path.mkdir() for object-oriented approach
from pathlib import Path
# Create directory using pathlib
new_dir = Path("pathlib_directory")
new_dir.mkdir(exist_ok=True)
print(f"Directory '{new_dir}' created")--OUTPUT--Directory 'pathlib_directory' created
The pathlib module offers a modern, object-oriented way to handle filesystem paths. Instead of using string-based functions, you create Path objects that represent the paths themselves. This approach makes your code cleaner and more intuitive, as you're working with path objects that have their own methods.
- The
.mkdir()method is called directly on thePathobject. - Like
os.makedirs(), it includes anexist_ok=Trueparameter to prevent errors if the directory already exists, making your scripts more resilient.
Handling existing directories gracefully
import os
import errno
try:
os.mkdir("my_directory")
print("Directory created successfully")
except OSError as e:
if e.errno == errno.EEXIST:
print("Directory already exists")
else:
raise--OUTPUT--Directory created successfully
Before the exist_ok parameter became common, this try...except block was the go-to method for handling potential errors. It lets your script attempt to create a directory with os.mkdir() and gracefully catches an OSError if the folder already exists, preventing the program from crashing.
- The code inspects the error to see if it matches
errno.EEXIST. This specific error code confirms the directory’s existence, allowing your script to proceed as intended. - Using
raisein theelseblock is crucial. It ensures that any otherOSError, such as a permissions issue, will still stop the script and alert you to a real problem.
Advanced directory manipulation
With the fundamentals covered, you can now handle advanced tasks like managing temporary directories, setting permissions, and creating multiple folders at once.
Creating temporary directories with tempfile
import tempfile
import os
# Create a temporary directory that gets removed when closed
with tempfile.TemporaryDirectory() as temp_dir:
print(f"Created temporary directory: {temp_dir}")
# Files and directories inside temp_dir will be deleted automatically--OUTPUT--Created temporary directory: /tmp/tmpf8z2m49p
The tempfile module is your go-to for creating directories you don't need to keep. By using tempfile.TemporaryDirectory() in a with statement, you create a folder that automatically disappears after use, which is perfect for handling intermediate files without cluttering your filesystem.
- As soon as the
withblock completes, Python automatically deletes the directory and everything inside it. - This is incredibly useful for temporary storage during tasks like data processing or running tests, ensuring your script leaves no trace behind.
Setting permissions when creating directories
import os
import stat
# Create directory with specific permissions (read/write/execute for owner only)
os.mkdir("secure_dir")
os.chmod("secure_dir", stat.S_IRWXU)
print(f"Created directory with permissions: {oct(os.stat('secure_dir').st_mode)[-3:]}")--OUTPUT--Created directory with permissions: 700
For security-sensitive applications, you'll often need to control who can access a directory. Python handles this in two steps: you first create the directory with os.mkdir(), then set its permissions with os.chmod(). This function modifies the directory's access rights.
- The
statmodule provides easy-to-read constants for permissions. - In this example,
stat.S_IRWXUgrants read, write, and execute permissions (IRWX) only to the user (U) who owns the directory, effectively locking others out.
Creating multiple directories with list comprehension
import os
from pathlib import Path
# Create multiple directories at once
dir_names = ["dir1", "dir2", "dir3"]
[Path(d).mkdir(exist_ok=True) for d in dir_names]
print(f"Created directories: {', '.join(dir_names)}")--OUTPUT--Created directories: dir1, dir2, dir3
You can create multiple directories in a single, elegant line using a list comprehension. This Pythonic approach iterates through a list of names, making your code both compact and highly readable when you need to set up multiple folders at once.
- The expression loops through each string in the
dir_nameslist. - For each name, it creates a
Pathobject and immediately calls its.mkdir()method, combining object-oriented path handling with a concise loop.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the directory creation techniques we've explored, Replit Agent can turn them into production-ready tools:
- Build a file organizer that automatically sorts documents into nested folders by year and month.
- Create a project boilerplate generator that sets up a complete directory structure for a new web application.
- Deploy a data processing utility that uses temporary directories to safely handle intermediate files during a complex workflow.
Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.
Common errors and challenges
Even simple operations can lead to tricky errors, but understanding them is the first step toward writing more resilient code.
A common mistake is using os.mkdir() to create a directory inside a parent folder that doesn’t exist. Because os.mkdir() can only create one directory at a time, it will raise a FileNotFoundError. To fix this, use os.makedirs(), which recursively creates all the necessary parent directories in the path for you.
You’ll encounter a PermissionError if your script tries to create a directory in a protected location, like the root directory, without the proper access rights. This is the operating system preventing an unauthorized change. Your options are to either run the script with elevated privileges—for example, using sudo—or, more safely, choose a writable location like the user's home directory.
A subtle but critical issue is the race condition. This happens if you check for a directory’s existence with os.path.exists() and then immediately try to create it with os.mkdir(). Another process could create the directory in the split second between your check and your creation attempt, causing an error. To avoid this, it's better to just try creating it and handle the potential failure.
- The most robust solution is to use the
exist_ok=Trueparameter, available in bothos.makedirs()andpathlib.Path.mkdir(). - Alternatively, you can wrap the
os.mkdir()call in atry...except FileExistsErrorblock to gracefully catch the error if the directory already exists.
Handling errors with non-existent parent directories using os.mkdir()
The os.mkdir() function is intentionally simple, creating just one directory at a time. If you try to create a nested path where a parent directory is missing, Python will raise an error. The following code demonstrates this exact FileNotFoundError in action.
import os
# This will fail if 'non_existent_parent' doesn't exist
os.mkdir("non_existent_parent/child_directory")
Because the non_existent_parent directory is missing, the os.mkdir() function cannot create child_directory within it and raises an error. The code below demonstrates the correct way to build this path.
import os
# Use makedirs to create all necessary parent directories
os.makedirs("non_existent_parent/child_directory", exist_ok=True)
The fix is to switch from os.mkdir() to os.makedirs(). This function recursively creates all missing parent directories in the path, so you don't have to build them one by one. Adding the exist_ok=True argument prevents errors if the directories already exist. This approach is ideal when your script generates a nested folder structure for organizing files, like logs or user data, and you can't guarantee the parent folders are already in place.
Fixing permission issues with os.mkdir() in protected locations
Attempting to create a directory in a protected area of the filesystem, like a system folder, is a common source of errors. Without the right permissions, your script won’t be allowed to make changes, triggering a PermissionError.
The code below demonstrates a scenario where os.mkdir() fails because it lacks the necessary access rights.
import os
# This might fail due to insufficient permissions
os.mkdir("/system_directory/my_folder")
This code fails because it tries to create my_folder in /system_directory, a path that usually requires administrator rights. The operating system blocks the action, triggering the error. See how to handle this correctly in the code below.
import os
# Create in a location where you have write permissions
user_home = os.path.expanduser("~")
os.mkdir(os.path.join(user_home, "my_folder"))
The fix is to create the directory in a location where your script has write permissions. The code uses os.path.expanduser("~") to dynamically find the current user's home directory—a safe and writable location. It then uses os.path.join() to construct the full path, avoiding the PermissionError entirely. It’s a much safer approach than running your script with elevated privileges, especially in production environments where security is a top priority.
Avoiding race conditions with os.path.exists() and os.mkdir()
A race condition happens when you check if a directory exists with os.path.exists() right before creating it with os.mkdir(). Another process can create the directory in that split second, causing your script to fail. The code below shows this vulnerable pattern.
import os
# Race condition: Another process might create the directory between check and creation
if not os.path.exists("shared_directory"):
os.mkdir("shared_directory")
This pattern is unreliable because the check and creation are two separate steps. Another process can create the directory between the os.path.exists() call and the os.mkdir() call, causing an error. The following example demonstrates a safer method.
import os
# Use try-except to handle race conditions elegantly
try:
os.mkdir("shared_directory")
except FileExistsError:
pass # Directory already exists, which is fine
The best way to avoid a race condition is to attempt the operation directly and handle the potential error. This try...except block tries to create the directory with os.mkdir(). If the directory already exists, Python raises a FileExistsError, which the except block catches and silently ignores using pass. This approach is atomic—it's a single, uninterruptible step—and guarantees your code won't crash. It's much safer than checking for the directory's existence first.
Real-world applications
With a solid grasp on handling errors, you can now build powerful, real-world tools for organization and automation.
Creating backup directories with timestamps using datetime
A classic use case is creating timestamped directories for backups. This ensures that each backup is saved in its own unique folder, preventing accidental overwrites and making it easy to find a specific version. You can achieve this by combining a directory creation function with Python’s built-in datetime module.
First, you get the current time with datetime.now(). Then, you format it into a string that works as a valid folder name using the strftime() method—for example, something like "backup_2023-10-27_15-30-00". Finally, you pass this string to os.makedirs() or pathlib.Path.mkdir() to create a neatly organized, timestamped archive every time your script runs.
Setting up a project directory structure with pathlib
When you start a new project, you often need a standard set of folders, such as src for source code, tests for tests, and docs for documentation. Creating these manually is tedious, but you can automate the entire process with a simple Python script using the pathlib module.
Because pathlib treats paths as objects, your code becomes much cleaner. You can define your desired structure in a list of strings, loop through it, and create each directory inside your main project folder. By calling .mkdir(parents=True, exist_ok=True) on each path object, your script becomes robust, creating any necessary parent folders and running without errors even if the directories already exist.
Creating backup directories with timestamps using datetime
You can create a unique directory for each backup by generating a timestamp with the datetime module and using it as part of the folder's name.
import os
from datetime import datetime
# Create a backup directory with current timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_dir = f"backup_{timestamp}"
os.mkdir(backup_dir)
print(f"Created backup directory: {backup_dir}")
This code generates a unique directory name using the current date and time, making it perfect for creating versioned backups. It’s a straightforward process:
- The
datetime.now()function captures the exact moment the script runs. - Next,
strftime()formats this into a clean, file-safe string like20231027_153000. - An f-string then constructs the final directory name, which
os.mkdir()uses to create the folder.
This technique ensures every backup is stored in a distinct directory, preventing accidental overwrites.
Setting up a project directory structure with pathlib
You can automate project setup by defining your desired folder structure in a list and using pathlib to create each directory.
import os
from pathlib import Path
# Create a standard Python project structure
project_name = "my_new_project"
base_dir = Path(project_name)
base_dir.mkdir(exist_ok=True)
# Create standard project subdirectories
subdirs = ["src", "tests", "docs", "data"]
for subdir in subdirs:
(base_dir / subdir).mkdir(exist_ok=True)
print(f"Created project structure for {project_name}")
print(f"Directories: {', '.join([str(base_dir / d) for d in subdirs])}")
This script leverages the pathlib module to build a clean project structure. It creates a main project directory and then loops through a list of standard subfolders like src and tests, creating each one inside the main folder.
- The forward slash operator (
/) is a special feature ofpathlibthat lets you intuitively join path components together. - Calling
mkdir(exist_ok=True)on each path prevents the script from crashing if the directories already exist, making it reliably re-runnable.
This object-oriented approach makes your setup scripts both readable and robust.
Get started with Replit
Turn your knowledge into a real tool. Describe what you want to build to Replit Agent, like “a script that creates timestamped backup folders” or “a project generator for my web apps.”
Replit Agent writes the code, tests for errors, and deploys your application right from your browser. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)