How to Check if a File Exists in Python?

In Python, you can check if a file exists by using several methods. Here are a few of the most common methods:

Using the os.path module

This is one of the traditional ways to check if a file exists.

import os.path

if os.path.isfile('/path/to/file'):
    print("File exists.")
else:
    print("File does not exist.")

Using the os module

This method checks if a path exists. It can be used for both files and directories.

import os

if os.path.exists('/path/to/file'):
    print("Path exists.")
else:
    print("Path does not exist.")

If you specifically want to ensure it’s a file and not a directory:

if os.path.exists('/path/to/file') and os.path.isfile('/path/to/file'):
    print("File exists.")
else:
    print("File does not exist.")

Using the pathlib module (Python 3.4 and newer)

The pathlib module provides an Object-Oriented interface to the filesystem and is recommended for newer Python versions.

from pathlib import Path

file_path = Path('/path/to/file')
   
if file_path.exists() and file_path.is_file():
    print("File exists.")
else:
    print("File does not exist.")