Here are two ways to create a directory if it does not exist in Python:
- Using os.path.exists() and os.makedirs()
- Using os.path.isdir() and os.makedirs()
Method 1: Using os.path.exists() and os.makedirs()
This approach first checks if the directory exists using os.path.exists(). If the directory does not exist, os.makedirs() is used to create it.
The os.makedirs() can also create intermediate directories if they don’t exist.
If the directory exists, then it will throw a FileExistsError exception.
Example
Before creating a directory, our directory looks like this:
import os
def create_recursive_dir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
create_recursive_dir(
"/Users/krunallathiya/Desktop/Code/pythonenv/newdir/folder")
Output
Example 2: Using “exist_ok” argument of the makedirs() function
The makedirs() function accepts the exist_ok argument, which prevents the function from raising an error by setting it to True if the directory already exists.
To avoid FileExistsError, either use the os.path.exists() function or exist_ok parameter.
import os
def create_recursive_dir(dir_path):
os.makedirs(dir_path, exist_ok=True)
create_recursive_dir("/Users/krunallathiya/Desktop/Code/R/sf/match")
If you rerun this code, it won’t throw any error. However, if you set the exist_ok to False, it throws FileExistsError.
import os
def create_recursive_dir(dir_path):
os.makedirs(dir_path, exist_ok=False)
create_recursive_dir("/Users/krunallathiya/Desktop/Code/R/sf/match")
Output
FileExistsError: [Errno 17] File exists: '/Users/krunallathiya/Desktop/Code/R/sf/match'
Either set make_exist = True or use the os.path.exists() function to avoid FileExistsError.
Method 2: Using isdir() and makedirs() methods
In this approach, os.path.isdir() is used to check if the path exists and is a directory. If it’s not, os.makedirs() is used to create the directory.
Example
import os
def create_recursive_dir(dir_path):
if not os.path.isdir(dir_path):
os.makedirs(dir_path)
create_recursive_dir(
"/Users/krunallathiya/Desktop/Code/pythonenv/newdir/folder2")
Output
That’s it.
SoftBigs
I found this article helpful. Thank you for writing it!
John Davis
Great blog post! I’m glad to see a detailed explanation of how to create a directory if it doesn’t exist in Python. This is a useful technique that I will definitely use in my own projects. Thanks for sharing!
Krunal
Thanks Davis, keep learning and sharing!