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:
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.
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.
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 program to remove special characters from a string
- How to append a list, tuple or set to a set in python
- Python find the base name of a given path
- Python dictionary get() method explanation with example
- Python program to check if a path exists
- Python os.path.lexists() method explanation with example