Open In App

Python | os.path.isdir() method

Improve
Improve
Like Article
Like
Save
Share
Report

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 module is a sub-module of the OS module in Python used for common path name manipulation.

os.path.isdir() method in Python checks whether the specified path is a directory or not. This method follows the symbolic link, which means if the specified path is a symbolic link pointing to an existing directory then the method will return True.

Syntax

os.path.isdir(path) 

Parameter

: A path-like object representing a file system path. 

Return Type

This method returns a Boolean value of class bool. This method returns True if the specified path is an existing directory, otherwise returns False.

Note: isdir() stands for “is directory”, which justifies its task for checking if the given path is a directory.

Example 1: Using os.path.isdir() method

Python3




# importing os.path module
import os.path
path = '/home/User/Documents/file.txt'
# Check whether the specified path is an existing directory or not
isdir = os.path.isdir(path)
print(isdir)
path = '/home/User/Documents/'
isdir = os.path.isdir(path)
print(isdir)


Output

False
True

Example 2: Check if the path is a directory using a symbolic link

Python3




import os.path
# Create a directory
os.mkdir("GeeksForGeeks")
# Create a symbolic link pointing to above directory
os.symlink("GeeksForGeeks", "/home/User/Desktop/gfg")
# Check whether the specified path is an existing directory or not
print(os.path.isdir("GeeksForGeeks"))
# Check whether the specified path is an existing directory or not
print(os.path.isdir("/home/User/Desktop/gfg"))


Output

True
True

We have covered how to use os.path.isdir() method of OS module to check if the given path is a directory or not. Python isdir() method returns true if the given path is a directory otherwise returns false.

It is useful to check for directories before performing any operations on it. We have explained isdir() method in very easy words, with examples of Python programs. You can easily learn and practice isdir() method using this guide.



Last Updated : 11 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads