Python Script To Check If A Directory Exists, If Not, Create It

In this article, we will create a Python script which will check if a particular directory exists on our machine or not if not then the script will create it for us with built in Python functions.

Check If A Directory Exists, If Not, Create It

The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.

os.path.isdir(): Method used for checking if a given directory exists or not.
os.makedirs(): The method used for creating a directory.

Program

'''Check if directory exists, if not, create it'''
import os

# You should change 'test' to your preferred folder.
MYDIR = ("test")
CHECK_FOLDER = os.path.isdir(MYDIR)

# If folder doesn't exist, then create it.
if not CHECK_FOLDER:
    os.makedirs(MYDIR)
    print("created folder : ", MYDIR)

else:
    print(MYDIR, "folder already exists.")

Output

created folder :  test

Explanation

First, we are importing the OS module next we are declaring the directory which we will look for you should change it to your preferred directory or folder name.

Then we are using the os.path.isdir(MYDIR) method and looking for our folder on the system and below that we have a set of conditional operation which creates a new directory with a given name using os.makedirs(MYDIR) method if the isdir() method evaluates to false.

Note that the folder or directory will be generated at the location where the script exists.

Related Articles

Leave a Reply

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

Close