Python | os.path.isdir() method
Last Updated :
11 Mar, 2024
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
import os.path
path = '/home/User/Documents/file.txt'
isdir = os.path.isdir(path)
print (isdir)
path = '/home/User/Documents/'
isdir = os.path.isdir(path)
print (isdir)
|
Example 2: Check if the path is a directory using a symbolic link
Python3
import os.path
os.mkdir( "GeeksForGeeks" )
os.symlink( "GeeksForGeeks" , "/home/User/Desktop/gfg" )
print (os.path.isdir( "GeeksForGeeks" ))
print (os.path.isdir( "/home/User/Desktop/gfg" ))
|
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...