Examples of File Not Found Error in Python: 3 Practical Examples (Plus More You Actually See)

If you work with files in Python long enough, you will absolutely run into a `FileNotFoundError`. Instead of treating it like a mystery, it helps to walk through real examples of file not found error in Python: 3 practical examples that mirror what people actually hit in day‑to‑day coding. These examples of file not found issues show up in data analysis, web apps, automation scripts, and even simple learning projects. In this guide, we’ll start with three core, practical scenarios and then branch into more real examples: missing CSV files in data pipelines, mis-typed log paths in production, user-uploaded files that don’t exist on disk, and path problems that only appear on Windows or Linux. Along the way, you’ll see how to read the traceback, how to fix the path, and how to handle the error gracefully instead of letting your script crash. The goal is simple: after reading this, `FileNotFoundError` should feel boring, predictable, and easy to debug.
Written by
Jamie
Published
Updated

When people ask for examples of file not found error in Python: 3 practical examples, this is always first: you call open() on a path that doesn’t exist, and Python throws FileNotFoundError.

## data_report.py

file_path = "data/report.csv"

with open(file_path, "r", encoding="utf-8") as f:
    content = f.read()
    print("Report length:", len(content))
``

Run this from the wrong directory and you get:

```text
Traceback (most recent call last):
  File "data_report.py", line 5, in <module>
    with open(file_path, "r", encoding="utf-8") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data/report.csv'

This is the best example of how path assumptions break:

  • You thought data/report.csv was relative to your project root.
  • Python treated it as relative to your current working directory.
  • If you run python scripts/data_report.py from the project root, it might work.
  • If you run python data_report.py from inside scripts/, the relative path is now wrong.

Fixing it with project‑relative paths

A more reliable pattern uses the script’s directory as an anchor:

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
file_path = BASE_DIR / ".." / "data" / "report.csv"

with open(file_path, "r", encoding="utf-8") as f:
    content = f.read()
    print("Report length:", len(content))

Now the path is stable no matter where you run the script from. When people look for examples of file not found error in Python: 3 practical examples, this “wrong working directory” case is the one professionals see every week in real codebases.


2. Data science in 2024: Jupyter notebooks and missing CSVs

In 2024–2025, a huge share of Python work happens in notebooks. That means a huge share of FileNotFoundError bugs come from running a notebook in one folder while your data lives in another.

Here’s a very common example of this in a Jupyter notebook:

import pandas as pd

## You *think* the notebook lives in the same folder as data.csv

df = pd.read_csv("data.csv")
print(df.head())

If the notebook is saved in notebooks/ and data.csv is actually in data/, you get:

FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'

This is one of the best examples of how environment and tooling affect file paths. In VS Code or JupyterLab, your working directory might be the project root; in a cloud notebook environment, it might be your home directory or a mounted volume.

Safer pattern with Path

from pathlib import Path
import pandas as pd

NOTEBOOK_DIR = Path().resolve()  # current working directory
DATA_PATH = NOTEBOOK_DIR.parent / "data" / "data.csv"

if not DATA_PATH.exists():
    raise FileNotFoundError(f"Expected data file at {DATA_PATH}")

df = pd.read_csv(DATA_PATH)

This pattern also plays nicely with data versioning tools and reproducible research practices that are increasingly common in 2024, especially in academic and scientific settings (see, for example, guidance on reproducible workflows from institutions like Harvard University).

Again, when we talk about examples of file not found error in Python: 3 practical examples, the notebook‑plus‑CSV combo is absolutely in the top three.


3. Web apps and user uploads: a production‑grade practical example

The third of our core examples of file not found error in Python: 3 practical examples comes from web applications. Think Flask or Django: a user uploads a file, you store its path in the database, then later you try to read it. If the file was cleaned up, moved, or never fully written, you get FileNotFoundError right in the request handler.

## Flask-style handler
from flask import send_file, abort
from pathlib import Path

UPLOAD_DIR = Path("/var/www/uploads")

@app.get("/download/<filename>")
def download(filename):
    file_path = UPLOAD_DIR / filename

    try:
        return send_file(file_path)
    except FileNotFoundError:
        abort(404, description="File not found on server")

This kind of real example shows how FileNotFoundError becomes a user‑visible 404 error. In production, this might be caused by:

  • A background cleanup job deleting old uploads.
  • A mismatch between the path in the database and the actual folder structure.
  • A deployment that changed UPLOAD_DIR without migrating old data.

The fix is not just “catch the error.” It’s about:

  • Validating that paths exist before storing them.
  • Using stable, versioned directories for uploaded content.
  • Logging the error with context so you can trace which user and which upload failed.

In other words, the third of our best examples is less about a typo and more about lifecycle and infrastructure.


Beyond the 3: more real examples that trigger FileNotFoundError

Those three cases cover most beginner and intermediate pain, but there are more real‑world patterns you should know. These examples include platform differences, typos, and timing issues.

Case: Windows vs. Linux path differences

A Windows‑only developer hardcodes a path like this:

log_path = "C:\\logs\\app.log"

with open(log_path, "a", encoding="utf-8") as f:
    f.write("App started\n")

This works locally, then fails in a Linux Docker container with:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\logs\\app.log'

Linux doesn’t have a C: drive, so there is literally no way that path can exist. This is a textbook example of environment‑specific assumptions.

A better pattern:

from pathlib import Path

LOG_DIR = Path("/var/log/myapp") if not Path("C:/").exists() else Path("C:/logs")
LOG_DIR.mkdir(parents=True, exist_ok=True)

log_path = LOG_DIR / "app.log"

with open(log_path, "a", encoding="utf-8") as f:
    f.write("App started\n")

Using Path keeps your code portable and reduces the chance of FileNotFoundError when you change operating systems.

Case: Typos and case sensitivity

On Windows, Data.csv and data.csv are often treated the same by tools, which hides mistakes. On Linux and macOS, file systems are typically case‑sensitive.

from pathlib import Path

file_path = Path("Data.csv")  # But the real file is data.csv

with open(file_path, "r", encoding="utf-8") as f:
    print(f.read())

On a case‑sensitive system, this is another straightforward example of file not found error in Python. The fix is sometimes as boring as agreeing on naming conventions and using linting or CI checks to enforce them.

Case: Race conditions in concurrent code

In multi‑process or multi‑threaded systems, one worker may delete a file while another tries to read it. This is less common for beginners but very real in 2024 cloud workloads.

from pathlib import Path

path = Path("/tmp/session_123.json")

if path.exists():
#    # Another process might delete the file right here
    with open(path, "r", encoding="utf-8") as f:
        data = f.read()  # FileNotFoundError can still happen

The correct pattern is to assume FileNotFoundError can happen even after exists() and handle it:

try:
    with open(path, "r", encoding="utf-8") as f:
        data = f.read()
except FileNotFoundError:
    data = None  # Or log and continue

This is a more advanced, but very real, example of why checking exists() is not a silver bullet.

Case: Misconfigured config files and environment variables

A lot of modern Python apps use environment variables or config files to specify paths. Misconfiguration is a quiet source of FileNotFoundError.

import os
from pathlib import Path

DATA_DIR = Path(os.getenv("MYAPP_DATA_DIR", "./data"))
file_path = DATA_DIR / "config.json"

with open(file_path, "r", encoding="utf-8") as f:
    config = f.read()

If MYAPP_DATA_DIR points to a non‑existent folder on a staging server, you get another real example of this error. The fix is to validate configuration at startup and fail fast with a clear message.


Reading the traceback: turning examples into a debugging habit

The reason we walk through these examples of file not found error in Python: 3 practical examples (plus extras) is to build a repeatable mental checklist.

When you see:

FileNotFoundError: [Errno 2] No such file or directory: 'path/here.ext'

Ask yourself:

  • Is the path relative or absolute?
  • Relative to what? (Current working directory? Script location?)
  • Does the directory exist, or just the file name in your head?
  • Are you on a different OS than the person who wrote the path?
  • Is there any chance another process deleted or moved the file?

Python’s standard library docs for file objects and path handling are worth bookmarking for reference: see the official Python I/O documentation and the pathlib module docs. These are not just theory; they’re the reference behind every example of file not found error in Python you’ll ever hit.


Preventing FileNotFoundError in new code

Learning from these examples is good; not repeating them is better. A few practical habits:

  • Use pathlib.Path instead of raw strings for paths.
  • Anchor paths to a known base (project root, config directory, or environment variable).
  • Validate configuration and required files at startup.
  • In user‑facing apps, catch FileNotFoundError and convert it into a helpful message or HTTP 404.
  • In data pipelines, log missing files with enough metadata (job ID, dataset name, timestamp) to investigate.

Many software engineering and data science courses, including those from universities like MIT OpenCourseWare and Harvard, emphasize reproducible environments and predictable file layouts for exactly this reason: fewer FileNotFoundError surprises.


FAQ: common questions about FileNotFoundError in Python

What are some real examples of FileNotFoundError in Python?

Real‑world examples include:

  • A script trying to open data/report.csv from the wrong working directory.
  • A Jupyter notebook calling pd.read_csv("data.csv") when the file lives in a sibling folder.
  • A Flask or Django app serving user uploads from a path that no longer exists.
  • A Windows‑style hardcoded path like C:\\logs\\app.log running on Linux.
  • A background job deleting a file while another worker tries to read it.

These are the same patterns that informed the examples of file not found error in Python: 3 practical examples earlier in this article.

Can I avoid FileNotFoundError by always checking if a file exists first?

Not entirely. Path.exists() helps catch obvious mistakes, but in concurrent systems a file can disappear between the exists() check and the open() call. The safer approach is:

  • Use exists() for early validation where it makes sense.
  • Still wrap open() in a try/except FileNotFoundError block when the file might be modified by other processes.

What is the best example of handling FileNotFoundError gracefully?

One of the best examples is a web route that tries to serve a file and, if it’s missing, returns a 404 page instead of a 500 crash:

from flask import send_file, abort

try:
    return send_file(file_path)
except FileNotFoundError:
    abort(404, description="File not available")

This pattern keeps your logs informative while giving the user a clear, predictable response.

Why does my script work in one folder but raise FileNotFoundError in another?

Because relative paths are resolved against the current working directory, not the script’s location. If you rely on "data/report.csv", running the script from different folders will produce different results. Using Path(__file__).parent (or a well‑defined project root) to build paths avoids this trap, as shown in several examples of file not found error in Python earlier in this guide.

Is FileNotFoundError always about files, or can directories cause it too?

Directories can absolutely be involved. If you try to open "logs/app/app.log" but the logs/app/ directory doesn’t exist, Python raises FileNotFoundError because it can’t even reach the file location. Creating parent directories with Path(...).mkdir(parents=True, exist_ok=True) before writing is a simple way to avoid this class of error.

Explore More File Not Found Errors

Discover more examples and insights in this category.

View All File Not Found Errors