Skip to content

FileNotFoundError: no such file or directory

Quick summary

You tried to open a file that does not exist at the given path — Python raises FileNotFoundError with the path it could not find.

Why this happens

  • The file path is misspelled or uses incorrect directory separators for the operating system

  • The file has not been created yet, or was deleted or moved before the open call

  • The script's working directory is different from what you expect, making a relative path resolve to the wrong location

Minimal example

✗ Broken code
with open('data/input.txt') as f:  # FileNotFoundError
    content = f.read()
✓ Fixed code
from pathlib import Path
p = Path('data/input.txt')
if not p.exists():
    print(f'File not found: {p.absolute()}')
else:
    content = p.read_text()

Checking existence with pathlib before reading gives a clear error message with the absolute path, and avoids the raw FileNotFoundError.

How to diagnose

  • Print os.getcwd() to confirm the current working directory and construct the full path with os.path.abspath()

  • Use os.path.exists() or pathlib.Path.exists() to check if the file exists before opening it

  • Print the exact path string to inspect for typos, extra spaces, or wrong separators

How to fix

  • Correct the file path spelling and use os.path.join() or pathlib to build cross-platform paths safely

  • Create the file first with open(path, 'w') if it should exist, or verify the download/copy step completed

  • Use an absolute path instead of a relative path to avoid working directory ambiguity

How to prevent

  • Use pathlib.Path for path construction to avoid separator and encoding issues across platforms

  • Check file existence with Path.exists() and provide a clear error message before calling open()

Related Resources

Related Glossary

Related Lessons

← Back to language