You can check whether a file exists in Python without raising an error by using the os.path.exists() function or the Path.exists() method from the pathlib module. Here’s how to do it using both methods:
Method 1: Using os.path.exists():
import os
file_path = "your_file_path_here"
if os.path.exists(file_path):
print("The file exists.")
else:
print("The file does not exist.")
Replace “your_file_path_here” with the path to the file you want to check.
Method 2: Using pathlib.Path.exists():
from pathlib import Path
file_path = "your_file_path_here"
if Path(file_path).exists():
print("The file exists.")
else:
print("The file does not exist.")
Again, replace “your_file_path_here” with the path to the file you want to check. The pathlib module is available in Python 3.4 and later, and it provides a more modern and convenient way to work with file paths.
Method 3: Using try except blocks:
import os
file_path = "your_file_path_here"
try:
if os.path.isfile(file_path):
print("The file exists.")
else:
print("The file does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
All these methods will return True if the file exists and False if it doesn’t, without raising an error.