How to check if a path is file or directory in Python

Python program to check if a path is file or directory:

In this post, we will learn how to check if a given path is a directory or file. Python os module provides different sub-modules and methods related to the operating system.

os.path is a sub-module of os. It has few useful functions on pathnames. This sub-module provides two methods that we can use to check if a path is file or directory. This is the easiest way to check for a path is file or directory in python, because we don’t have to install and use any third party library.

Below are the two methods defined in os.path that can be used to check if a path is file or directory in python:

os.path.isfile(path):

This method checks if a path is a file or not. It returns one boolean value. True if the given path is a file. Else, False.

It returns True for symbolic links.

os.path.isdir(path):

This method checks if a path is a directory or not. It returns one boolean value. True if the given path is a directory. Else, False.

Similar to the above one, it returns True for symbolic links.

Example python program to check if a path is file or directory:

Let’s take a look at the below program:

import os

first_path = "/Users/cvc/Downloads/programs"
second_path = "/Users/cvc/Downloads/programs/example.py"

print(os.path.isfile(first_path))
print(os.path.isdir(first_path))

print(os.path.isfile(second_path))
print(os.path.isdir(second_path))

It will print the below output:

False
True
True
False

Here, first_path is the path of a directory and second_path is the path of a file.

python check path is file or directory

You might also like: