1. Python

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?

Comments to: How to check if Directory exists in Python

Your email address will not be published.

Ads