Checking whether a file exists in Python

You can use os.path.isfile() to check both whether a name both exists and is a file:

from os.path import isfile

if isfile('file.txt'):
    # Do something with file.txt

To check for the existence of any type of filesystem object, use os.path.exists():

from os.path import exists

if exists('path'):
    # Do something with path

Note that it isn’t a good idea to check for a file’s existence before opening it – it’s a race condition, with the file able to disappear in-between you testing for its existence and opening it.

It’s much better (and more Pythonic) to just try to open it and handle failure:

    with open('file.txt') as f:
        # Do something with f
except IOError as err:
    # Handle the err