Kodeclik Logo

Learn More

Summer 2025

Kodeclik Blog

Checking for File Existence in Python

When working with files in Python, it's best practice to check if a file exists before you do something with it, e.g., before you read, write, or update it. This helps prevent errors and keeps your programs running smoothly. Python offers several built-in ways to do this, using both the classic os.path module and the more modern pathlib, as well as by handling exceptions. Here are five different approaches you can use to check if a file exists in Python.

Python check if file exists

Method 1: Use os.path.isfile()

To check specifically if a filename points to an existing file, use os.path.isfile().

import os

if os.path.isfile("example.txt"):
    print("The file exists and is a file.")
else:
    print("File does not exist or is not a file.")

This approach calls os.path.isfile("example.txt"), which returns True only if "example.txt" exists and is a regular file, not a directory or special device. It's useful when you need to ensure you're working with a file—not another type of path—and helps avoid errors when processing files versus folders. If the result is False, either the file doesn't exist or the path points to something else (like a directory).

Method 2: Use os.path.exists()

To verify if any filesystem path—file or directory—exists, use os.path.exists().

import os

if os.path.exists("example.txt"):
    print("The path exists.")
else:
    print("The path does not exist.")

This function will return True for both files and directories, so it's more general-purpose than os.path.isfile(). It simply checks that something at the specified path is present. If you need to act regardless of whether it's a file or a folder, or if you're unsure of the type, os.path.exists() is the right choice. False means nothing exists there at all.

Method 3: Use pathlib.Path.exists()

The modern pathlib module offers an object-oriented way to check if a file or path exists.

from pathlib import Path

file_path = Path("example.txt")
if file_path.exists():
    print("File exists!")
else:
    print("File does not exist.")

Creating a Path object with Path("example.txt") and calling its .exists() method offers straightforward, readable code and works for both files and directories. This approach aligns with newer Python best practices (from Python 3.4+) and can be chained with more advanced pathlib methods. The result is True if anything (file, folder, link) exists at the given path; otherwise, False.

Method 4: Use a try-except block

If you want to follow Python’s “Easier to Ask Forgiveness than Permission” (EAFP) principle, try opening the file and catch an exception if it fails.

try:
    with open("example.txt") as f:
        print("File exists!")
except FileNotFoundError:
    print("File does not exist.")

Here, the code attempts to open "example.txt" directly within a try block. If the file exists and can be opened, the code inside runs normally; if not, a FileNotFoundError is caught and handled gracefully. This method is especially useful when you'd need to open the file anyway—such as reading or modifying its contents—and helps catch permission problems alongside non-existence.

Method 5: Use os.access() for permission-specific checks

If you want to check not only if the file exists but also if it’s accessible, use os.access() with the os.F_OK flag.

import os

if os.access("example.txt", os.F_OK):
    print("File exists.")
else:
    print("File does not exist.")

os.access("example.txt", os.F_OK) checks for the file’s existence and is commonly paired with other flags for permission checks (like reading, writing, executing). This is especially useful in environments with restricted user permissions. Note that this test doesn't guarantee future access—race conditions may occur between the check and subsequent file operations—but it’s a way to preempt common errors when working with protected files.

All the methods above help you safely manage files across all your Python projects and choose the best approach for your specific needs.

Note that most of the methods above primarily check for the existence of a file or path. Except for Method 5 (and perhaps Method 4 which can help catch errors via exception handling), they do not guarantee that the program has the necessary permissions to access or modify the file.

What to Do If a File Does Not Exist

If a file does not exist, depending on your program, you might explore other strategies for handling missing files, e.g., creating a new empty file, prompting for user action, or logging a warning and skipping the operation. This helps developers create resilient programs that don't crash or lose data when a file is missing.

Cross-Platform Considerations

Different operating systems manage paths and file systems differently. For instance, Windows uses backslashes (“\”) whereas Linux and UNIX use forward slashes (“/”). Also some file systems are case-sensitive but others are not. You have to take these into account as you write your code so that there are no errors or surprises.

Security and Permission Issues

It’s important to note that file existence checks don’t guarantee future access if permissions change or files are deleted in the meantime. Thus, it is always good to do these checks just before more detailed accesses are conducted.

Summary

In summary, understanding how to check for the existence of files in Python is essential for writing robust, error-free code. By leveraging built-in modules like os.path and pathlib, and using functions such as isfile() and their object-oriented counterparts you can write robust code. This will help you prevent errors and ensure smooth execution in any environment.

Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2025. All rights reserved.