HOWTO · Python

How to Check if a File Exists in Python

This how-to article introduces how to check if a file exists in Python. Explore various methods such as os.path.exists(), pathlib, and try-except blocks with clear examples to enhance your coding skills and prevent errors in your applications.

On this page

A regular-file check is useful when your next step depends on a path naming a file rather than a directory. For a pathlib path, use Path.is_file(). It returns a Boolean and follows symbolic links to regular files. A check is only a snapshot: the path can change before a later operation, so open the file directly when you are ready to use it.

Quick answer: Check whether the path is a file

Run this example to check a regular file created by the program:

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "notes.txt"
    path.write_text("Hello, Python!", encoding="utf-8")
    print(path.is_file())

The temporary directory keeps the example self-contained. Path.is_file() is the clearest choice when the question is specifically whether the path names a regular file. The result is True for a regular file and False when the path is missing, names a directory, or cannot be confirmed as a regular file.

Use pathlib.Path.is_file()

pathlib represents filesystem paths as Path objects, so this method fits code that already uses pathlib. Create a path from a string or combine a directory path with a filename using /, then call is_file():

from pathlib import Path

path = Path("reports") / "summary.txt"
if path.is_file():
    print("A regular file is available.")

This snippet shows the check without assuming that reports/summary.txt exists in the reader’s environment. It does not open or read the file. Filesystem permission or operating-system errors can affect what a check can confirm, so do not use a false result as a diagnosis of why access failed.

Use os.path.isfile()

For code that uses os.path, call its isfile() function with a path. It has the same regular-file purpose as Path.is_file():

import os

path = os.path.join("reports", "summary.txt")
if os.path.isfile(path):
    print("A regular file is available.")

os.path.isfile() is a function, while Path.is_file() is a method on a Path object. Choose the form that matches the surrounding code; both distinguish regular files from directories.

Choose exists() when directories also count

Use Path.exists() or os.path.exists() when you only need to know whether a path exists, whether it is a file or a directory. Both can return True for directories, so they are broader than a regular-file check. For example, use Path("reports").exists() when either a file or directory at that location is acceptable, and use Path("reports").is_file() when only a regular file qualifies.

These checks do not guarantee that a later read or write will succeed. The path may change after the check, and existence does not establish that your process has permission to use it. If the operation itself is what matters, perform that operation and handle its relevant errors.

Open the file directly when you will use it

When reading is the next step, opening directly avoids relying on a check that may become stale. Catch FileNotFoundError only when you want to handle a missing path; let permission and other I/O errors remain visible or handle them separately according to the application:

from pathlib import Path

path = Path("settings.json")
try:
    with path.open(encoding="utf-8") as file:
        contents = file.read()
except FileNotFoundError:
    contents = None

if contents is None:
    print("The settings file is missing.")
else:
    print("The settings file was read.")

This pattern both attempts the intended read and handles absence specifically. It does not treat PermissionError or another OSError as proof that the path is missing. Use the check-first pattern when you need to report or branch on path type; use direct opening when you intend to read the file now.