Skip to content

How to Check If a File Exists in Python

Learn how to verify file existence in Python using os.path.exists() (legacy) or pathlib.Path.exists() (modern) to avoid FileNotFoundError and handle paths correctly.

Before attempting to read from or write to a file in Python, it is crucial to verify its existence. Trying to access a non-existent file will raise a FileNotFoundError, crashing your script. Python provides robust tools for this, primarily via the classic os.path module and the modern pathlib object-oriented library.

This guide explains absolute versus relative paths and demonstrates two reliable methods for checking file existence.

Understanding File Paths (Absolute vs. Relative)

A file path tells the computer where a file is located.

  • Absolute Path: The full address starting from the root (e.g., /home/user/project/data.txt or C:\Users\Name\data.txt). It works regardless of where your script is running.
  • Relative Path: The address relative to the Current Working Directory (e.g., data.txt or ../data.txt).
import os

cwd = os.getcwd()
print(f"Current Directory: {cwd}")

filename = "my_file.txt"

abs_path = os.path.join(cwd, filename)
print(f"Absolute Path: {abs_path}")

Method 1: Using os.path.exists() (Legacy)

The standard way to check for a file or directory in older Python code is using the os.path module. It returns True if the path exists (whether it's a file or a folder) and False otherwise.

import os

filename = "my_file.txt"

if os.path.exists(filename):
    print(f"'{filename}' exists.")
else:
    print(f"'{filename}' does not exist.")

if os.path.isfile(filename):
    print("It is definitely a file.")

Method 2: Using pathlib.Path.exists() (Modern)

Introduced in Python 3.4, pathlib offers an object-oriented approach. It is generally preferred for new projects because path objects are easier to manipulate (e.g., joining paths with /) and work consistently across operating systems.

from pathlib import Path

file_path = Path("my_file.txt")

if file_path.exists():
    print(f"'{file_path}' exists.")
    
    if file_path.is_file():
        print("It is a file.")
    elif file_path.is_dir():
        print("It is a directory.")
else:
    print(f"'{file_path}' does not exist.")

Conclusion

To check if a file exists in Python:

  1. Use pathlib.Path(path).exists() for modern, readable, object-oriented code.
  2. Use os.path.exists(path) if working with legacy codebases.
  3. Understand Paths: Remember that relative paths depend on where you run the script from (os.getcwd()).
Navigation