How to Use a Fallback Path with FileNotFoundError in Python

Read a primary file and fall back to a backup file when the first is missing, returning an empty string if both fail.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 12 views 0 copies

Python code

18 lines
Python 3.9+
import pathlib

def read_config(path):
    primary = pathlib.Path(path)
    fallback = pathlib.Path("config_backup.json")
    try:
        with primary.open("r") as f:
            return f.read()
    except FileNotFoundError:
        try:
            with fallback.open("r") as f:
                return f.read()
        except FileNotFoundError:
            return ""

if __name__ == "__main__":
    result = read_config("missing_config.json")
    print(result)

Output

stdout
{
  "retry_count": 3,
  "timeout": 30
}

How it works

The code wraps both file-open attempts in separate try/except blocks. The outer try tries the primary path and catches FileNotFoundError; the inner try tries the fallback and also catches FileNotFoundError. If both files are missing, it returns an empty string as the final fallback. Using pathlib.Path objects makes the file paths platform-independent and easier to compose.

Common mistakes

  • Catching the wrong exception type — FileNotFoundError is distinct from OSError.
  • Forgetting that pathlib.Path.open returns a context manager, so always use 'with'.
  • Nesting try/except blocks without a meaningful fallback result for the final case.

Variations

  1. Use os.path.exists() to check before opening, but that introduces a race condition.
  2. Use a list of paths and iterate with a for loop inside a single try/except.

Real-world use cases

  • Reading configuration in a service that keeps a default copy if the user-provided file is absent.
  • Loading training data from a current path with a backup snapshot behind it.
  • Fetching prompt templates where a local override file may not exist yet.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.