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

1 min read

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.


PROGRAMS

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read