How to Check if a File Exists in Python?
To check if a file exists in Python, you can use the os.path
module.
Here's an example:
import os
# specify the filename
filename = "example.txt"
# check if the file exists
if os.path.isfile(filename):
print(f"{filename} exists")
else:
print(f"{filename} does not exist")
In this example, we first import the os
module. Then we specify the filename as a string ("example.txt"
in this case).
We use os.path.isfile(filename)
to check if the file exists. If it does, we print a message saying that the file exists. If it doesn't, we print a message saying that it doesn't exist.