Python program to check and create one directory

Introduction :

Python OS module provides different methods to perform different operating system tasks like create a directory, delete a directory, etc. In this post, we will learn how to check if a directory exists or not and to create one directory if it doesn’t exist.

Methods to use :

We will use the python os module and the following methods of this module :

1. os.path.isdir(path) :

This method takes one argument, the path of the directory. It returns True if path is an existing directory. Else, it returns False.

2. os.mkdir :

This method is used to create one directory. We can pass the path of a directory to this method and it will create one as defined by the path. It throws one FileExistsError if the folder already exists.

Python program :

Below python program will check if a folder exists or not in the current directory and create it if it doesn’t exist.

import os

DIR_NAME = "Example-dir"

if os.path.isdir(DIR_NAME):
    print(DIR_NAME, "already exists.")
else:
    os.mkdir(DIR_NAME)
    print(DIR_NAME, "is created.")

This program will create one directory in the same folder.

We can wrap the mkdir line in a try-catch block if we don’t use the if condition.

Python example check create directory

Similar tutorials :