How to Check if a File Exists in Python?

As a developer working on a project for a client in the United States, I recently encountered a situation where I needed to verify the existence of a file before processing it. In this tutorial, I will explain how to check if a file exists in Python using various methods. I will share my experience and the solutions I discovered.

Check if a File Exists in Python

Let us learn how to check if a file exists in Python.

Read How to Print the Contents of a File in Python?

Use the os.path Module

Python’s built-in os.path module provides several functions to work with file paths, including checking if a file exists. Here are two commonly used methods:

1. os.path.exists()

The os.path.exists() function checks if a file or directory exists at the specified path. It returns True if the path exists, regardless of whether it’s a file or a directory, and False otherwise. Here’s an example:

import os

file_path = 'data/customers_usa.csv'

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

I executed the above example code and added the screenshot below.

Check if a File Exists in Python

In this example, we import the os module and specify the file path as 'data/customers_usa.csv'. We then use the os.path.exists() function to check if the file exists. If it does, we print a message indicating its existence; otherwise, we print a message stating that the file does not exist.

2. os.path.isfile()

If you specifically want to check if a path points to a file (not a directory), you can use the os.path.isfile() function. It returns True if the path is a file and False otherwise. Here’s an example:

import os

file_path = 'data/customers_usa.csv'

if os.path.isfile(file_path):
    print(f"The path {file_path} points to a file.")
else:
    print(f"The path {file_path} does not point to a file.")

I executed the above example code and added the screenshot below.

How to Check if a File Exists in Python

This example is similar to the previous one, but instead of using os.path.exists(), we use os.path.isfile() to specifically check if the path points to a file.

Check out Python Get File Extension

Use the pathlib Module

Python’s pathlib module provides an object-oriented approach to working with file paths. It offers the Path class, which has methods to check if a file exists. Let’s explore two commonly used methods:

1. Path.exists()

The Path.exists() method checks if a file or directory exists at the specified path. It returns True if the path exists and False otherwise. Here’s an example:

from pathlib import Path

file_path = Path('data/customers_usa.csv')

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

I executed the above example code and added the screenshot below.

Check if a File Exists in Python Path.exists()

In this example, we import the Path class from the pathlib module and create a Path object representing the file path. We then use the exists() method to check if the file exists.

Read How to Import a Class from a File in Python

2. Path.is_file()

Similar to os.path.isfile(), the Path.is_file() method checks if a path points to a file (not a directory). It returns True if the path is a file and False otherwise. Here’s an example:

from pathlib import Path

file_path = Path('data/customers_usa.csv')

if file_path.is_file():
    print(f"The path {file_path} points to a file.")
else:
    print(f"The path {file_path} does not point to a file.")

This example uses the is_file() method to specifically check if the path points to a file.

Check out How to Copy File and Rename in Python

Handle File Not Found Error

When working with files, it’s important to handle potential errors gracefully. One common error is the FileNotFoundError, which occurs when you try to open a file that doesn’t exist. Here’s an example of how you can handle this error:

file_path = 'data/customers_usa.csv'

try:
    with open(file_path, 'r') as file:
        # Process the file
        print("Processing the file...")
except FileNotFoundError:
    print(f"The file {file_path} does not exist.")

In this example, we use a try-except block to catch the FileNotFoundError. If the file exists, the code inside the try block is executed, and we can process the file. If the file doesn’t exist, the except block is executed, and we print an error message.

Read How to Read Tab-Delimited Files in Python?

Conclusion

In this article, I explained how to check if a file exists in Python. I discussed how to use the os.path module with functions like os.path.exists() and os.path.isfile(), and use the pathlib module with methods like Path.exists() and Path.is_file(). Additionally, I covered how to handle potential errors, such as the FileNotFoundError, to ensure your code runs smoothly.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.