How can I create a directory if it does not exist using Python?



Python has built-in file creation, writing, and reading capabilities. In Python, there are two sorts of files that can be handled: text files and binary files (written in binary language, 0s, and 1s). While you can create files, you may delete them when you no longer need them.

We can also create directories using Python. It is simple to create directories programmatically, but you must ensure that they do not already exist. You'll have difficulties if you don't.

Following are different ways to create directories using Python if they do not exist -

Using os.path.exists() with os.makedirs()

In Python, we use the os.path.exists() method to see if a directory already exists, and then use the os.makedirs() method to create it.

The built-in Python method os.path.exists() is used to determine whether or not the supplied path exists. The os.path.exists() method produces a boolean value that is either True or False, depending on whether or not the route exists.

Python's OS module includes functions for creating and removing directories (folders), retrieving their contents, altering and identifying the current directory, and more. To interface with the underlying operating system, you must first import the os module.

Example

The following example creates a directory using the os.makedirs() method -

#python program to check if a directory exists
import os
path = "directory"
# Check whether the specified path exists or not
isExist = os.path.exists(path)
#printing if the path exists or not
print(isExist)

On executing the above program, the following output is generated -

False 

Example: with the exist_ok parameter

The built-in Python method os.makedirs() is used to recursively build a directory.

#python program to check if a directory exists
import os
path = "pythonprog"
# Check whether the specified path exists or not
isExist = os.path.exists(path)
if not isExist:
   # Create a new directory because it does not exist
   os.makedirs(path)
   print("The new directory is created!")
else:
   print("Directory already exists!")

On executing the above program, the following output is generated -

The new directory is created!

Running the code again would produce the following output -

Directory already exists!

Example: Using an if Statement

To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using -

#python program to check if a path exists
#if it doesn't exist we create one
import os
if not os.path.exists('my_folder'):
   os.makedirs('my_folder')
   print("Created directory: my_folder")
else:
   print("Directory my_folder already exists")

On executing the above program, the following output is generated -

Created directory: my_folder

Using pathlib.Path().mkdir()

The pathlib module contains classes that represent filesystem paths and provide semantics for various operating systems.

Pure paths, which give purely computational operations without I/O, and concrete paths, which inherit from pure pathways but additionally provide I/O operations, are the two types of path classes.

Example

The following example creates a directory using the makedir() method -

# python program to check if a path exists
# if path doesn't exist we create a new path
from pathlib import Path
# creating a new directory called pythondirectory
path = Path("pythondirectory_pathlib")
if not path.exists():
    path.mkdir(parents=True, exist_ok=True)
    print(f"Created directory: {path}")
else:
    print(f"Directory already exists: {path}")

On executing the above program, the following output is generated -

Created directory: pythondirectory_pathlib

Example: try/except with os.makedirs()

We can also use exception handling to find out whether the directory already exists.

When we are creating a directory using the makedirs() function, if the given directory already exists, this method raises an exception named FileExistsError.

We can catch the raised exception (using try and except) and print the message if the file already exists, and proceed with the rest of the program.

Example

In the following example, we are using the os.makedirs() to create a directory, and if the directory already exists, a FileExistsError exception is caught and handled -

# python program to check if a path exists
# if path doesn't exist we create a new path
import os
try:
   path = "try_except_directory"
   os.makedirs(path)
   print(f"Successfully created directory: {path}")
except FileExistsError:
   # directory already exists
   print(f"Directory already exists: {path}")

On executing the above program, the following output is generated -

Successfully created directory: try_except_directory
Updated on: 2025-05-28T14:08:21+05:30

299K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements