Here are two ways to create a directory if it does not exist in Python:
- Using os.makedirs() and os.path.exists()
- Using isdir() and makedirs()
Method 1: Using os.makedirs() and os.path.exists() methods
The os.makedirs() method creates all intermediate-level directories.
To check if a directory exists, use the “os.path.exists()” function. If the directory exists, then it will throw a FileExistsError exception.
Example
Before creating a directory, our directory looks like this:
Run the below code.
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 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 = 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
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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
I found this article helpful. Thank you for writing it!