How to Check if Directory Exists using Python

Muhammad Waiz Khan Feb 02, 2024
  1. Check if Directory Exists Using path.isdir() Method of os Module in Python
  2. Check if Directory Exists Using path.exists() Method of os Module in Python
How to Check if Directory Exists using Python

This tutorial will look into various methods in Python to check if a specific directory exists or not. Suppose we have a program that saves a file in a specific directory and if the directory does not exist, it creates it first. For this, we need a method to check if a specific directory exists or not.

Check if Directory Exists Using path.isdir() Method of os Module in Python

The path.isdir() method of the os module takes a path string as input and returns True if the path refers to an existing directory and returns False if the directory does not exist on that path.

Suppose we want to check if the directory myfolder exists at the path /testfolder/myfolder, the path.isdir() method will return True if the directory myfolder exists at the path, otherwise it will return False.

The example code below demonstrates the use of the path.isdir() method:

import os

os.path.isdir(r"/testfolder/myfolder")

Check if Directory Exists Using path.exists() Method of os Module in Python

The path.exists() method of the os module in Python takes a path as input and returns True if the path refers to an existing path and returns False otherwise. It is different from the path.isdir() method as it also works for files.

Unlike the path.isdir() method, the path.exists() method checks not only the directory but also the file exists. And to check the existence of a directory, we will have to give the path of that directory like /testfolder/myfolder.

The code example below demonstrates the use of the path.exists() method for both file and directory:

import os

os.path.exists("Desktop/folder/myfolder")
os.path.exists("Desktop/folder/myfile.txt")
Warning
The path.exists() method can not distinguish between a path of a directory or a file, in case there is a file named myfolder with no extension, in the path Desktop/folder/myfolder the path.exists() method will return True.

Related Article - Python Directory