Python: how to check if a file exists

Posted in Python by Dirk - last update: Jan 04, 2024

In Python, you can check if a file exists using the os.path module, which provides a function called path.exists(). As an alternative, you could also use the the pathlib module (as of Python 3.4) that can do the same.

Using the os.path Module

The os.path module provides 2 functions to check if a file exists.

Using os.path.exists()

The function os.path.exists() returns True if the path (file or directory) exists, and False otherwise. Example:

import os

file_path = '/path/to/your/file.txt'

if os.path.exists(file_path):
    print(f'The file {file_path} exists.')
else:
    print(f'The file {file_path} does not exist.')

The advantage of this method is that it can be used to check for both files and directories.

Using os.path.isfile()

The function os.path.isfile() returns True if the path points to a regular file, and False otherwise.

Example:

import os

file_path = '/path/to/your/file.txt'

if os.path.isfile(file_path):
    print(f'{file_path} is a file.')
else:
    print(f'{file_path} is not a file or does not exist.')

This method will only check the existence of a file, it will not work for directories

It does have a counterpart for directories (os.path.isdir(path)) which returns True if the path points to a directory, and False otherwise.

Using the ‘Path’ class from the ‘pathlib’ module

You need to import the Path class from the pathlib module first

from pathlib import Path

A simple example on how to use it for check if a file exists:

from pathlib import Path

file_path = Path('/path/to/your/file.txt')

if file_path.exists():
    print(f'The file {file_path} exists.')
else:
    print(f'The file {file_path} does not exist.')

In this example, Path('/path/to/your/file.txt') creates a Path’ object representing the file path, and then the exists() method is called on that object to check if the file exists. If the file exists, it prints a message indicating so; otherwise, it prints a message indicating that the file does not exist.

You need to replace /path/to/your/file.txt with the actual path of the file you want to check. This approach is more modern and readable than using the older os.path module, especially when dealing with paths in a platform-independent manner.

References

Other articles