How to Fix FileNotFoundError: [Errno 2] No Such File or Directory in Python

FileNotFoundError: [Errno 2] No such file or directory means Python tried to open a path that does not exist at that moment. The error message always prints the exact path. Compare that path with what is really on disk, and you usually find a renamed, moved, or never-created file.

Start this project - freeLive cloud workspace in your browser · lands on your portfolio
DevOps Engineerlinuxpythonfiles

What the error tells you

A typical traceback looks like this:

Traceback (most recent call last):
  File "/srv/app/app.py", line 19, in config
    with open(CONFIG_PATH, 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: '/srv/app/config.json'

Three facts are in that message:

The error does not say why the file is missing. That is your job.

Step 1: reproduce it and read the log

If the error happens inside a web app, the HTTP response is only a 500. The traceback is in the application log:

curl -i http://localhost:8080/config
tail -n 20 /var/log/app/app.log

Copy the path from the last line of the traceback.

Step 2: compare the path with what is on disk

ls -la /srv/app/

Look for a file with a similar name. Common patterns:

If the file is not in that folder at all, search for it:

find / -name 'config.json*' -not -path '/proc/*' 2>/dev/null

Step 3: put the file back

When you find the file, move it back to the path the code expects:

mv /srv/app/config.json.bak /srv/app/config.json

If the app opens the file on every request (as in the traceback above), the next request works with no restart. If the app reads the file only once at startup, restart the process after you restore the file.

Then confirm:

curl -i http://localhost:8080/config     # expect HTTP 200

Relative paths: the other common cause

If the path in the error is relative, the file may exist, but Python is looking in a different directory. This happens when a script is started from cron, systemd, or a different shell folder:

# Breaks when the working directory is not the script's folder
open('config.json')

# Works from any working directory
from pathlib import Path
BASE = Path(__file__).resolve().parent
open(BASE / 'config.json')

Print os.getcwd() next to the failing open() to see which directory Python is really using.

Make the app fail early and clearly

An app that only fails when a user hits an endpoint is hard to debug. Check required files at startup and exit with a clear message:

import sys
from pathlib import Path

CONFIG_PATH = Path('/srv/app/config.json')
if not CONFIG_PATH.is_file():
    sys.exit(f'FATAL: config file missing: {CONFIG_PATH}')

Now a missing file stops the deploy right away, with the path in the log, instead of returning 500 to users hours later.

Debugging habit: what changed outside the code?

When "nothing changed in the code" but the app broke overnight, look at the things around the code: file names, permissions, disk space, environment variables, and DNS. Logs plus ls and find answer most of these questions faster than reading code that did not change.

Do this project yourself. It's ready in a live cloud workspace in your browser - when you finish, it lands on your portfolio.

Start this project - free

What you'll practice

FAQ

What does FileNotFoundError: [Errno 2] No such file or directory mean?

It means Python asked the operating system to open a path and nothing exists at that path. Errno 2 is the system error ENOENT. The path in quotes at the end of the message is the exact path Python tried.

Why does Python say the file does not exist when I can see it?

Usually the path is relative and Python resolves it against the current working directory, not the script's folder. Other causes are a different letter case (Linux is case-sensitive) or a hidden character in the name. Use an absolute path built from Path(__file__).resolve().parent.

Do I need to restart the app after restoring the file?

Only if the app reads the file once at startup. If it opens the file on each request, the next request picks it up with no restart.

How do I find a file that was moved or renamed on Linux?

List the folder with ls -la and look for names like .bak or .old. If it is not there, run find / -name 'filename*' 2>/dev/null to search the whole system.

Keep learning

Recover a Crashed Linux ServiceDevOps projectFix a Docker Container That Exits ImmediatelyDevOps projectFix the CRLF Line Endings Breaking start.shDevOps projectDevOps roadmapStep by step to hiredDevOps interview questionsSTAR answersAll DevOps projectsProjects hub

Do this project yourself. It's ready in a live cloud workspace in your browser - when you finish, it lands on your portfolio.

Start this project - free
Start this project - free