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.
Python code
18 linesimport 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
{
"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
- Use os.path.exists() to check before opening, but that introduces a race condition.
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.