The os.path.exists() method in Python is used to check whether a specified path exists.
This method checks for the existence of files, directories, and even symlinks. For symlinks, it checks the existence of the path the symlink points to.
This method is extremely helpful in file system operations where you need to verify the existence of a path before taking action, such as opening a file, writing to a path, or performing directory operations.
This method works across different platforms (Windows, Linux, macOS).
Syntax
os.path.exists(path)
Parameters
Name | Description |
path (string) | It is the path you want to verify. |
Return Value
It returns True if the path argument refers to an existing path (a file, a directory, or a valid symlink). Otherwise, it returns False.
Example 1: Checking if a file exists
Here is a file (data.txt) in the current working directory that we will check:
import os
path = "/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt"
if os.path.exists(path):
print("File exists.")
else:
print("File does not exist.")
Output
File exists.
Example 2: Checking if a directory exists
Here is a directory (env) that we will check:
import os
dir_path = "/Users/krunallathiya/Desktop/Code/pythonenv/env/"
if os.path.exists(dir_path):
print("Directory exists.")
else:
print("Directory does not exist.")
Output
Directory exists.
Example 3: Checking for non-existent path
import os
path = "/Users/krunallathiya/Desktop/Code/pythonenv/env/non_existent.txt"
if os.path.exists(path):
print("File exists.")
else:
print("File does not exist.")
Output
File does not exist.
That’s it!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.