How do I check whether a file exists without exceptions in Python?

In Python, you can check whether a file exists without raising any exceptions by using the os.path.exists() function from the built-in os module. This function takes a file path as its argument and returns True if the file exists, and False otherwise.

Here’s an example of how to use os.path.exists() to check whether a file exists:

import os

file_path = "path/to/file.txt"

if os.path.exists(file_path):
    print("The file exists!")
    print("The file does not exist.")

In this example, we import the os module and define a file path using the variable file_path. We then use the os.path.exists() function to check whether the file exists. If the file exists, the program will print “The file exists!”. Otherwise, it will print “The file does not exist.”.

Note that os.path.exists() can also be used to check whether a directory exists. If the argument passed to os.path.exists() is a directory path instead of a file path, the function will return True if the directory exists, and False otherwise.

Leave a Reply

Your email address will not be published. Required fields are marked *