Python os.path.isdir() method is used to check if a specified path points to an existing directory.
Syntax
os.path.isdir(path)
Parameters
Name | Description |
path (string) | The path you want to check. |
Return Value
- It returns True if the path exists and is a directory.
- It returns False if the path does not exist or is not a directory.
- It returns True if the path is a symbolic link pointing to a directory.
- It returns False if the path is a file and not a directory.
Example 1: Checking if a Path is a Directory
Here is a screenshot of a directory path we want to check:
import os
path = '/Users/krunallathiya/Desktop/Code/pythonenv/env'
is_directory = os.path.isdir(path)
print(is_directory)
Output
True
Example 2: Path does not exist
import os
path = '/path/to/nonexistent/directory'
is_directory = os.path.isdir(path)
print(is_directory)
Output
False
Example 3: Checking for symlinks
Here is a symbolic path link (symlink) that points to the actual directory:
import os
path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/symlink'
is_directory = os.path.isdir(path)
print(is_directory)
Output
True
Example 4: Path is a file, not a directory
import os
path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/file.txt'
is_directory = os.path.isdir(path)
print(is_directory)
Output
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. It returns True whether the argument is a file name or folder. If it exists, then it returns True.
Related posts
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.