Python File Does Not Exist Exception

When I was working with files in Python, one of the most common errors I faced was the File Does Not Exist exception. If you’ve ever tried to open a file that wasn’t there, you’ve likely seen the dreaded FileNotFoundError.

It can be frustrating, especially when you’re building something important like a log processor, a report generator, or even a simple data pipeline.

I’ve learned multiple ways to handle this error gracefully. In this tutorial, I will show you five practical Python methods to handle the “file does not exist” exception.

Method 1 – Use Try and Except Block in Python

The most direct way to handle a missing file in Python is by using a try-except block. I use this method when I want to attempt opening a file, but also want to handle the error gracefully if it doesn’t exist.

# Method 1: Using try-except to handle FileNotFoundError

try:
    with open("usa_sales_data.txt", "r") as file:
        content = file.read()
        print("File content loaded successfully!")
except FileNotFoundError:
    print("Error: The file does not exist. Please check the file name or path.")

You can see the output in the screenshot below.

python file does not exist

Here, Python tries to open usa_sales_data.txt. If the file is missing, it catches the FileNotFoundError and prints a friendly error message instead of crashing.

Method 2 – Use os.path.exists() in Python

Another reliable way is to check if the file exists before opening it. Python’s built-in os.path.exists() function helps me confirm whether the file is available.

# Method 2: Using os.path.exists()

import os

file_path = "usa_employee_records.csv"

if os.path.exists(file_path):
    with open(file_path, "r") as file:
        print("File found. Reading data...")
        print(file.read())
else:
    print(f"Error: {file_path} does not exist.")

You can see the output in the screenshot below.

python file not found exception

This approach is cleaner when I want to verify the file before doing anything else with it. I often use this method in production scripts where missing files should trigger alerts.

Method 3 – Use pathlib.Path.exists() in Python

In modern Python (3.4+), I prefer using the pathlib module because it’s more intuitive and object-oriented. With pathlib, checking and handling missing files becomes elegant and readable.

# Method 3: Using pathlib.Path.exists()

from pathlib import Path

file_path = Path("usa_inventory_data.json")

if file_path.exists():
    with open(file_path, "r") as file:
        print("File found. Processing inventory data...")
        print(file.read())
else:
    print(f"Error: {file_path} not found in the directory.")

You can see the output in the screenshot below.

python if file does not exist

I personally like this method because it integrates well with other file operations, such as creating new files or directories.

Method 4 – Create the File If It Does Not Exist in Python

Sometimes, instead of throwing an error, I want Python to create the file automatically if it doesn’t exist. This is useful in logging systems or when I’m generating reports.

# Method 4: Create the file if it does not exist

import os

file_path = "usa_logs.txt"

if not os.path.exists(file_path):
    with open(file_path, "w") as file:
        file.write("Log file created.\n")
        print("File did not exist. A new log file has been created.")
else:
    with open(file_path, "a") as file:
        file.write("Appending new log entry.\n")
        print("File exists. Added a new log entry.")

You can see the output in the screenshot below.

file does not exist

This way, I never have to worry about missing log files in my automation scripts.

Method 5 – Use Exception Handling with Custom Error Message in Python

Finally, I sometimes want to raise my own custom error when a file is missing. This makes sense in larger applications where I want to give developers or users more context.

# Method 5: Raise custom exception for missing file

import os

file_path = "usa_customer_data.xlsx"

if not os.path.exists(file_path):
    raise FileNotFoundError(f"Custom Error: The file '{file_path}' is missing. Please upload it before running the program.")
else:
    with open(file_path, "r") as file:
        print("Customer data loaded successfully.")

This method is powerful because it allows me to control the error flow and provide detailed instructions.

Which Method Should You Use?

  • Try-Except (Method 1): Best for quick error handling.
  • os.path.exists() (Method 2): Great for pre-checks before opening files.
  • pathlib (Method 3): Modern, clean, and Pythonic.
  • Create File (Method 4): Perfect for logging or report generation.
  • Custom Exception (Method 5): Ideal for larger applications with strict error handling.

Conclusion

Handling the Python File Does Not Exist exception is something every developer faces sooner or later. The good news is that Python gives us multiple ways to deal with it, from simple try-except blocks to more advanced techniques with pathlib and custom exceptions.

Personally, I find myself using pathlib more often these days because it makes the code more readable and future-proof. Next time you run into a missing file in Python, try one of these five methods. They’ll save you time, prevent crashes, and make your scripts more reliable.

You may also like to read other Python tutorials:

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.