Check if a file or directory exists in Python

Last modified: 
Wednesday, July 1st, 2015
Topics: 
Python
import os

path = "path/to/resource"

# True if path points to a file OR directory.
if os.path.exists(path):
    print "%s exists!" % (path)
else:
    print "%s not found" % (path)


# True if path points to a directory.
if os.path.isdir(path):
    print "%s exists!" % (path)
else:
    print "%s not found" % (path)


# True if path points to a file.
if os.path.isfile(path):
    print "%s exists!" % (path)
else:
    print "%s not found" % (path)


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.