How do you check if a path is a directory in Python?

How do you check if a path is a directory in Python?

a) By using the os.path.isdir() function
b) By using the os.path.isfile() function
c) By using the os.listdir() function
d) By using the os.path.exists() function

Answer:

a) By using the os.path.isdir() function

Explanation:

The os.path.isdir() function in Python is used to check if a given path is a directory. This function returns True if the path is a directory and False otherwise.

import os

# Example of checking if a path is a directory
path = "example_directory"
if os.path.isdir(path):
    print(f"{path} is a directory.")
else:
    print(f"{path} is not a directory.")

In this example, the os.path.isdir() function checks if example_directory is a directory and prints the appropriate message.

Checking if a path is a directory is useful when performing operations that depend on whether a path is a file or a directory, such as navigating directory structures or validating inputs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top