How to check if a Directory or file exists in Python

os.path module in Python

The OS module in Python provides a way of using operating system dependent functionality. We can use this module to open a file for read or write operation. Similarly it is providing os.path module to manipulate the path of the directories and files.

os.path.isdir(path) to check directory exists

The os.path.isdir(path) function returns True if a path is an existing directory. It will return False if the given directory doesn’t exist or if it is a file.

os.path.isfile(path) to check file exists

The os.path.isfile(path) function returns True if a path is an existing file. It will return False if the given file doesn’t exist or if it is a directory.

os.path.exists(path) to check both directory or file exists

The os.path.exists(path) function returns True if either a path is an existing directory or file. It will return False if the given path is not valid or given file or directory doesn’t exists.

Python – To check Directory exists or not

Here we are checking the java bin directory path that is exists or not in the system. Since the given directory is exists in the system,the os.path.isdir(path) function returns True and it prints the Directory exists message.

Output

Python – To check File exists or not

Here we are checking the java.exe file that is exists or not in the system. Since the given java.exe file is exists in the system,the os.path.isfile(path) function returns True and it prints the File exists message.

Output

Python – To check Directory or File exists or not

The os.path.exists(path) function is used here to validate the given path(file/directory) exists or not. Then the program print the corresponding messages as below.

Output

Lets given the invalid path for the dir_path and file_path variable as below and run the program

Output

To check Directory or File exists in Python
To check Directory or File exists in Python