Skip to content

How to Fix FileNotFoundError: [Errno 2] in Python

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix FileNotFoundError: [Errno 2] in Python. We cover key concepts, practical examples, and best practices.

Python raises FileNotFoundError: [Errno 2] No such file or directory when you try to open a file that does not exist at the specified path.

The Wrong Way

with open("data.csv", "r") as f:
    content = f.read()

This produces:

Traceback (most recent call last):
  File "script.py", line 1, in <module>
    with open("data.csv", "r") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'

The Right Way

Check if the file exists before opening it:

import os

filename = "data.csv"
if os.path.exists(filename):
    with open(filename, "r") as f:
        content = f.read()
else:
    print(f"File {filename} not found")

Output:

File data.csv not found

Step-by-Step Fix

1. Verify the current working directory

import os
print("Current directory:", os.getcwd())
print("Files:", os.listdir('.'))

2. Use absolute paths

import os

filepath = os.path.abspath("data.csv")
print("Looking for:", filepath)

if os.path.exists(filepath):
    with open(filepath, "r") as f:
        content = f.read()

3. Use pathlib for cleaner paths

from pathlib import Path

filepath = Path("data/data.csv")
if filepath.exists():
    content = filepath.read_text()
else:
    print(f"File not found: {filepath.resolve()}")

4. Create the file if needed

from pathlib import Path

filepath = Path("output.txt")
filepath.write_text("Default content")
print("File created")

Prevention Tips

  • Use os.path.exists() or Path.exists() before opening files.
  • Use absolute paths for production code.
  • Use pathlib.Path for cross-platform path handling.
  • Create required directories with Path.mkdir(parents=True, exist_ok=True).
  • Use try-except to handle missing files gracefully in user-facing applications.

Common Mistakes with filenotfound

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does Python not find my file even though it exists?

The file probably exists but not in the current working directory. Python looks for relative paths starting from where you ran the script, not where the script file is located. Use os.path.abspath() to debug the full path.

What is the difference between FileNotFoundError and IOError?

In Python 3, FileNotFoundError is a subclass of OSError. In Python 2, file errors used IOError. Python 3 replaced IOError with more specific subclasses like FileNotFoundError, PermissionError, and IsADirectoryError.

How do I handle FileNotFoundError when writing a file?

Writing opens the file in write or append mode and typically creates the file if it does not exist. However, if the parent directory does not exist, you get FileNotFoundError. Create the directory first with os.makedirs(dir, exist_ok=True).

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro