Check if Directory exists in Python
Python - Check if directory exists
To check if a directory exists in Python, you can use the os.path
library. Import os library, call the os.path.exists()
function and pass the path to directory as argument to the function.
The syntax to call os.path.exists() function to check if a directory exists
import os
os.path.exists('path/to/directory')
The function exists() returns a boolean value of True if the directory exists, or False if the directory does not exist.
Example
In the following program, we check programmatically if the directory myfolder/resources
exists or not using os.path.exists()
function.
Directory
We use the function call os.path.exists()
as a condition in the if-else statement.
Python Program
import os
path_to_directory = 'myfolder/resources'
if os.path.exists(path_to_directory):
print("Directory exists.")
else:
print("Directory does not exist.")
Output
Directory exists.
Summary
In this tutorial of Python Examples, we learned how to check if a directory exists or not using os.path.exists() function, with the help of examples.