Python FileNotFoundError
Open a receipt in a fresh workspace and handle the case where nobody has saved it yet.
A simple example
FileNotFoundError
- Start with No file named a.txt
- Do this Open a.txt for reading
- Result File missing
Syntax
except FileNotFoundError
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyRecover when a receipt is missing
A clerk requests a receipt before a new folder contains any exports. Handle that missing entry explicitly so the application can give the clerk a useful next action.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "today.txt"
try:
print(path.read_text(encoding="utf-8"))
except FileNotFoundError:
print("No receipt yet")
No receipt yet
The example deliberately uses an absent receipt. Permission failures and unrelated errors should still be visible.
Recover a seating plan that has yet to arrive
The school office expects a seating plan before an evening event. If the file has yet to arrive, the desk should tell the volunteer to check with the organizer and keep the sign-in station open.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as desk:
try:
print((Path(desk) / "seats.txt").read_text(encoding="utf-8"))
except FileNotFoundError:
print("Ask the organizer for the seating plan.")
Ask the organizer for the seating plan.
The empty temporary directory represents the desk before the plan arrives. Handling FileNotFoundError gives the volunteer a specific next action.
Read a saved shift record
The closing clerk saved the file before leaving. Open the expected file and show the desk whether it is available.
What to watch for
An existence check and a later open are separate operations. Handle failure at the point where the file is opened.