How to Create Directory If it Does Not Exist using Python?

We are back again. If you are searching create a directory if it does not exist using Python: We fix it!

Whether you’re organizing data, saving logs, or storing outputs, creating directories is essential. In Python, you can easily manage files as well as directories.

Let’s start with the guide about how to create a directory if it does not exist using Python.

How to Create a Directory If it Does Not Exist using Python

Creating a directory saves time and resources by not attempting to create something that’s already there. It makes your code cleaner and more organized by handling potential issues upfront.

To create a directory in Python, use the below steps:

Step 1: Import the Required Module

Python’s os module allows you to interface with the operating system. To construct directories, we utilize the os module. Start by importing it:

import os

Step 2: Define the Directory Path

Next, specify the path for the directory you want to create. This may be an absolute or relative path:

directory = "path/to/directory"

Step 3: Check if the Directory Exists

Before creating the directory, you can authenticate if it already exists through the os.path.exists():

if not os.path.exists(directory):
    os.makedirs(directory)
    print(f"Directory '{directory}' created successfully.")
else:
    print(f"Directory '{directory}' already exists.")

Here, os.path.exists(directory) checks if the directory exists. If it doesn’t, os.makedirs(directory) creates the directory. The print statements provide feedback on the operation.

Complete Code

Here’s a complete code:

import os

# Define the directory path
directory = "New Directory"

# Check if the directory exists
if not os.path.exists(directory):
    os.makedirs(directory)
    print(f"Directory '{directory}' created successfully.")
else:
    print(f"Directory '{directory}' already exists.")
Create a Directory If it Does Not Exist using Python

Using pathlib for a Modern Approach

Python’s pathlib module offers an object-oriented approach to handling filesystem paths. It’s available in Python 3.4 and later

Let’s see an example:

from pathlib import Path

# Define the directory path
directory = Path("New Directory 2")

# Check if the directory exists
if not directory.exists():
    directory.mkdir(parents=True, exist_ok=True)
    print(f"Directory '{directory}' created successfully.")
else:
    print(f"Directory '{directory}' already exists.")

In this example, Path(“New Directory 2”) creates a Path object. The exists() method checks if the directory exists, and mkdir(parents=True, exist_ok=True) creates the directory if it doesn’t.

Create a Directory If it Does Not Exist using pathlib Python

Conclusion

Whether you prefer the traditional os module or the modern pathlib approach, Python provides the tools you need to manage directories effectively. By checking for the directory’s existence before creating it, you can avoid errors and make your code more efficient and organized.

To create a directory if it does not exist in Python, use the os module with os.makedirs(directory, exist_ok=True). This ensures the directory is created only if it doesn’t already exist, avoiding errors and saving resources.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Scroll to Top