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
author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read