In this tutorial, you’ll learn how to use Python to create a directory if it doesn’t exist. Creating directories programmatically can save you a ton of time. However, not checking if the directory exists first can lead to significant problems, such as deleting files.
By the end of this tutorial, you’ll have learned:
- How to create a directory in Python if it doesn’t exist
- How to create nested directories if they don’t exist
Table of Contents
How to Create a Directory if It Doesn’t Exist in Python
The Python os
library allows you to work with the operating system, including the ability to check if a directory exists and, if not, create it. To create a directory in Python, we can use the makedir()
function. Let’s take a look at how we can create a directory:
# Creating a Directory in Python
import os
os.mkdir('sample')
The directory will be created if it doesn’t already exist in the path specified. If no path is explicitly stated, the directory will be made in the directory where your script is running.
However, if this directory already exists, a FileExistsError
will be raised. Let’s take a look at what happens when we run our script again:
# Raising an Error if the Directory Already Exists
import os
os.mkdir('sample')
# Raises: FileExistsError: [Errno 17] File exists: 'sample'
Because we didn’t handle the error, our program crashed. In order to create a directory if it doesn’t exist, we first need to check if it exists and if it doesn’t, we create it. Let’s see how we can use an if-else
block to accomplish this:
# Creating a Directory in Python if It Doesn't Exist
import os
if not os.path.exists('sample'):
os.mkdir('sample')
Let’s break down what we did above:
- We checked if the path already exists, using the
os.path.exists()
function - This returns a boolean value.
- If the value returned was
False
, then we move to the next step of creating the directory
The benefit of the above approach is that we’re handling the operation safely. It’s even more intuitive than using a try-except statement to handle the error.
How To Customize the os.makedirs() Function
Another function we can use to create a directory in Python is the os.makedirs()
function. The benefit of this function is that it has an argument, exists_ok=
, which prevents an error from being thrown if a given directory already exists.
Let’s take a look at how we can use this function to safely create a directory:
# How to Use the os.makedirs() Function
import os
os.makedirs('sample', exist_ok=True)
The benefit of this approach is cleaner code, though it may be less intuitive to people not as familiar with the os
library.
How to Create Nested Directories in it Doesn’t Exist in Python
In this section, you’ll learn how to create a nested directory if it doesn’t exist. Rather than needing to create a directory one at a time and moving into it, we can simply declare the nested path that we want to create. This is because the os.makedirs()
function behaves recursively to create these directories.
Let’s see how we can couple the exists_ok=
parameter with a nested directory. Recall that the parameter will prevent an error from being thrown if the directory already exists.
# Creating a Nested Directory if it Doesn't Exist
import os
os.makedirs('sample/data', exist_ok=True)
Because we passed in the exists_ok=
parameter, the function will override any error that is thrown if the directory already exists.
Conclusion
In this tutorial, you learned how to use Python to create a directory if it doesn’t already exist. Being able to work with and manipulate the file system in Python is an incredibly useful skill to develop. You learned how to use the os
library, including the os.mkdir() and os.makedirs() function to be able to create directories if they didn’t exist. Knowing different ways of accomplishing the task can make you a much more experienced and versatile programmer.
Additional Resources
To learn more about related topics, check out the tutorials below: