How to Tell if a File Exists in Python

Python helps make a lot of things really easy. The conciseness of the language make it awesome to accomplish simple tasks in as few lines as possible. One of these simple tasks is checking to see if a file exists.

import os file_path = '/full/path/to/file' if os.path.isfile(file_path): print('The file does exist. Yay!') else: print('The file does not exist. Boo!')

Here we utilize Python's built-in os.path module. Generally, the os module is useful because it works on all major platforms that Python runs on including Windows, Linux, and Mac OSX. We use os.path.isfile to ensure that both the file system paths exists and that it is a file instead of a directory. It is important to keep in mind that symlinks are considered files, so if your application can not read symbolic links you'll need to verify it is not a symlink by using the islink function.

Good luck and happy coding!