You can use the os.path.isfile() function to check whether a file exists in Python without exceptions. This function returns True if the specified path is an existing regular file, and False otherwise. Here’s an example:
import os
file_path = '/path/to/your/file.txt'
if os.path.isfile(file_path):
print("The file exists.")
else:
print("The file does not exist.")
In this example, the os.path.isfile() function is used to check whether the file at the specified file_path exists. If the file exists, the message “The file exists.” is printed. Otherwise, the message “The file does not exist.” is printed.
Note that os.path.isfile() can also be used to check whether a symbolic link or a non-regular file (e.g., a directory) exists at the specified path. If you want to check specifically for regular files, you can use the os.path.exists() function instead, which returns True for any existing path (file, directory, or symbolic link).
