Library contents

Python FileNotFoundError

Open a receipt in a fresh workspace and handle the case where nobody has saved it yet.

A simple example

FileNotFoundError

  1. Start with No file named a.txt
  2. Do this Open a.txt for reading
  3. Result File missing
The missing-path outcome lets the caller offer an empty starting state or ask for another name.

Syntax

Python 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.py

Recover 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 the programprint(path.read_text(encoding="utf-8"))
ResultNo receipt yet
lesson.py
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")
Output
No receipt yet

The example deliberately uses an absent receipt. Permission failures and unrelated errors should still be visible.

Advertisements

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 the programprint((Path(desk) / "seats.txt").read_text(encoding="utf-8"))
ResultAsk the organizer for the seating plan.
lesson.py
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.")
Output
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.

Givenrecord.txt exists
Worked resultFile 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.

Documentation for FileNotFoundError