How to check if a file or directory exists in Python using os.path.exists()?
Published on Aug. 22, 2023, 12:17 p.m.
To check if a file or directory exists in Python, you can use the os.path.exists()
method from the os
library. This method takes the path to the file or directory as its input and returns True
if the file or directory exists, and False
otherwise. Here is an example:
import os
path = "/path/to/file_or_directory"
if os.path.exists(path):
print("File or directory exists!")
else:
print("File or directory does not exist!")
This example checks if the file or directory located at /path/to/file_or_directory
exists using os.path.exists()
and prints an appropriate message to the console.
Note that os.path.exists()
returns True
for both files and directories, so if you need to check for the existence of a directory specifically, you can use os.path.isdir()
.
Using os.path.exists()
is useful when you need to check if a file or directory exists before performing operations on it, like opening, reading, writing, or deleting the file or directory.