How do I check whether a file exists without exceptions?

Created by rsliteLinked to 66.9m issues across 62 teams


Checking if a file exists can be done in a few different ways. The safest way is to use a try statement to attempt to open the file. If the file exists, the try statement will open it. If the file does not exist, an exception will be thrown.

Another way to check if a file exists is to use the os.path.isfile function. This function will return True if the path is an existing regular file. It will follow symbolic links, so both islink() and isfile() can be true for the same path. To use this function, you must first import the os.path module:

import os.path os.path.isfile(fname)