How to check if a Directory or file exists in Python
Contents
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.
1 2 3 4 5 6 7 8 |
import os dir_path = "C:\\Program Files\\Java\\jdk1.8.0_211\\bin" # Check directory exists or not using if condition if (os.path.isdir(dir_path)): print ("Directory exists") else: print ("Directory not exists") |
Output
1 |
Directory exists |
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.
1 2 3 4 5 6 7 8 |
import os file_path = "C:\\Program Files\\Java\\jdk1.8.0_211\\bin\\java.exe" # Check file exists or not using if condition if (os.path.isfile(file_path)): print ("File exists") else: print ("File not exists") |
Output
1 |
File exists |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import os dir_path = "C:\\Program Files\\Java\\jdk1.8.0_211\\bin" file_path = "C:\\Program Files\\Java\\jdk1.8.0_211\\bin\\java.exe" # To check Directory exists if (os.path.exists(dir_path)): print ("Directory exists") else: print ("Directory not exists") # To check File exits if (os.path.exists(file_path)): print ("File exists") else: print ("File not exists") |
Output
1 2 |
Directory exists File exists |
Lets given the invalid path for the dir_path and file_path variable as below and run the program
1 2 |
dir_path = "C:\\Program Files\\Java\\jdk1.8.0_211\\binary" file_path = "C:\\Program Files\\Java\\jdk1.8.0_211\\binary\\java.exe" |
Output