How to check if Directory exists in Python

For any given pathname, by using os and os.path module functions it can be checked whether directory exists or not. For this os.path.isdir(pathname) function from os.path module can be used.
Below is a Python code example showing How to check if Directory exists.

'''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 it doesn't exist then create it
if not CHECK_FOLDER:
    print(MYDIR, "folder already exists.")

But if you want to create a directory if it doesn’t exist then just need to use or.makedirs(pathname) function from os module.
Below is a Python Code example showing How to create a Directory if it doesn’t already exists.

'''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 it doesn't exist then create it
if not CHECK_FOLDER:
    os.makedirs(MYDIR)
    print("created folder : ", MYDIR)
 
else:
    print(MYDIR, "folder already exists.")

More about os Module => What is Python’s os Module?
More about os.path Module => What is os.path Module in Python?

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

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

Recent Posts