Python
Error Handling
FileNotFoundError
Troubleshooting
Programming

FileNotFoundError Errno 2 No such file or directory

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

FileNotFoundError: [Errno 2] No such file or directory means Python tried to open a path that does not exist from the program’s point of view. The fix is usually not complicated, but you need to verify the exact path, the current working directory, and whether the file or parent folder is supposed to exist yet.

What the Error Actually Means

This exception is a subclass of OSError. It appears when an operation such as open, Path.read_text, or os.listdir points at a path the operating system cannot find.

A simple example is:

python
with open("data/report.txt", "r", encoding="utf-8") as f:
    print(f.read())

If data/report.txt is missing, Python raises FileNotFoundError.

The important detail is that the path is evaluated relative to the current working directory unless you pass an absolute path.

The Current Working Directory Often Causes Confusion

Many developers assume a relative path is resolved relative to the script file. In reality, it is usually resolved relative to the process working directory.

This diagnostic helps immediately:

python
1from pathlib import Path
2import os
3
4print("cwd:", os.getcwd())
5print("exists:", Path("data/report.txt").exists())

If the current working directory is not what you expected, the relative path may point somewhere completely different.

A safer approach is to build paths relative to the script file:

python
1from pathlib import Path
2
3BASE_DIR = Path(__file__).resolve().parent
4REPORT_PATH = BASE_DIR / "data" / "report.txt"
5
6print(REPORT_PATH.read_text(encoding="utf-8"))

That makes the path independent of where the script was launched from.

Reading a Missing File vs Writing a New File

The error is common when reading a file, but it can also happen while writing if the parent directory does not exist.

This works only if the directory already exists:

python
with open("output/results.txt", "w", encoding="utf-8") as f:
    f.write("done")

If output does not exist, opening the file for writing still raises FileNotFoundError because Python cannot create intermediate directories automatically.

The fix is:

python
1from pathlib import Path
2
3output_dir = Path("output")
4output_dir.mkdir(parents=True, exist_ok=True)
5
6(output_dir / "results.txt").write_text("done", encoding="utf-8")

Prefer pathlib for Clarity

pathlib makes path handling easier to read and debug than hand-built string paths.

python
1from pathlib import Path
2
3config_path = Path("config") / "settings.json"
4
5if config_path.exists():
6    print(config_path.read_text(encoding="utf-8"))
7else:
8    print(f"Missing file: {config_path}")

This style avoids many mistakes involving slashes, escaped backslashes, and manual concatenation.

Windows Path Issues

On Windows, backslashes in normal string literals can create subtle bugs because sequences such as \n and \t are escape sequences.

This is risky:

python
path = "C:\new\test.txt"

A clearer option is a raw string or Path:

python
1from pathlib import Path
2
3path = Path(r"C:\new\test.txt")
4print(path.exists())

Using Path is generally the cleaner choice because it also keeps your code more portable.

A Practical Debugging Checklist

When you see Errno 2, verify these items in order:

  1. Print the full path you are trying to access.
  2. Print the current working directory.
  3. Check whether the file exists.
  4. Check whether the parent directory exists.
  5. Confirm the filename spelling and extension.

A small helper can make this concrete:

python
1from pathlib import Path
2
3path = Path("data/report.txt")
4print("resolved:", path.resolve())
5print("exists:", path.exists())
6print("parent exists:", path.parent.exists())

That usually tells you whether the problem is the file itself or the path calculation.

Common Pitfalls

One common mistake is using a relative path in code that runs from multiple locations, such as a local terminal, a test runner, and a production service.

Another pitfall is assuming write mode creates missing directories. It creates the file if possible, but not the directory tree above it.

Misspelled filenames and wrong extensions are also common, especially when files are generated by another step in the workflow.

Finally, developers sometimes mask the real issue by catching the exception too broadly. It is better to log the exact path and fix the path logic than to silently continue.

Summary

  • 'FileNotFoundError means the operating system could not find the requested path.'
  • Relative paths are resolved from the current working directory, not necessarily from the script file.
  • Use pathlib to build and inspect paths clearly.
  • Create parent directories before writing to nested output files.
  • Print the resolved path and existence checks first when debugging Errno 2.

Course illustration
Course illustration

All Rights Reserved.