To check if the directory exists or not in Python, use the os.path.dir() function. You can also check if the path is a file or directory using the os.path.isdir() function. To check if it is a file, use the os.path.isfile().
Python os.path.isdir()
The os.path.isdir() is a built-in Python function that is used to check whether the specified path is an existing directory or not. The isdir() function accepts a folder path as an argument and checks if it exists or not. If it exists, then returns True otherwise, False.
Syntax
os.path.isdir(path)
Argument
The isdir() function takes a path as a parameter.
Return Value
The method returns boolean values of either True or False.
Example
In my current directory, there is a folder called “tempA”. You can create any folder you want.
I will check that folder using the os.path.isdir() function.
import os path = "tempA" isdir = os.path.isdir(path) print(isdir)
Output
True
It returns True because the folder is there.
Now let’s pass a folder path that is not there and see the output.
import os path = "/Users/krunal/Desktop/code/pyt/apple" isdir = os.path.isdir(path) print(isdir)
Output
False
This is my current working directory’s full path, and it does not have an apple folder. So it returns False.
os.path.isdir() vs os.path.exists()
The os.path.isdir() method returns only True if that path exists and is a directory or a symbolic link to a directory. If it contains a file name, then it throws an error. It only works with folders or directories.
The os.path.exists() method returns True if there’s a regular file with that name. The os.path.exists() returns True whether the argument is a file name or folder. If it exists, then it returns True.
That is it for this tutorial.