How to Fix: FileNotFoundError: [Errno 2] No such file or directory

3D illustration of a searchlight finding an empty spot in a file cabinet, representing the FileNotFoundError in Python.

You tried to open a file in Python, but it crashed with this error, resulting in a FileNotFoundError Python message. However, understanding the common causes can help prevent this Python error from occurring.

It simply means: Python looked where you told it to, but nothing was there.

Cause 1: A Simple Typo (Most Common)

Did you type data.txt when the file is actually named Data.txt? Such small discrepancies can lead to a FileNotFoundError in Python.

  • Windows is often case-insensitive, but Mac/Linux are NOT.
  • Always check the exact spelling and capitalisation.
  • Check the extension! sometimes a file is named data.txt.txt if you have extensions hidden in Windows Explorer.

Cause 2: The “Relative Path” Trap (VS Code Users Beware!)

This is the #1 tricky cause. If your code is open("data.txt", "r"), Python only looks in the Current Working Directory (where you ran the command from). This is a common mistake that can trigger a FileNotFoundError Python when the expected file isn’t found in the location.

If your project looks like this:

/MyProject
    /code
        script.py
    data.txt

If you run the script from the /MyProject folder, it might fail because data.txt is NOT next to script.py.

The Fix: Use Absolute Paths so Python always knows exactly where to look, no matter where you run the script from.

import os

# Get the folder where THIS script.py file lives
script_dir = os.path.dirname(os.path.abspath(__file__))

# Build the full path to the data file securely
file_path = os.path.join(script_dir, "data.txt")

with open(file_path, "r") as f:
    print(f.read())

Summary

If you are sure the file exists, 99% of the time the issue is that Python is looking in the wrong folder. Use os.path.abspath to fix it and avoid a FileNotFoundError Python.

Similar Posts

Leave a Reply