Python os.path.isdir() Method

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

Python os.path.isdir() Method

Here is a screenshot of a directory path we want to check:

Screenshot of a directory for checking if a Path is a Directory

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

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

Checking for symlinks

Here is a symbolic path link (symlink) that points to the actual directory:

Screenshot of symlink folder

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

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

Python os.path.join()

Python os.path.split()

Python os.path.splitext()

Python os.path.isfile()

Python os.path.getsize()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.