──────────────────────────────────────

67. Weekly Activity Digest Capstone · Test the Report Before You Save It

Check repeated entries and write a new report file safely.

Lesson files · lessons/automation-capstone/test-and-package

Before you start
- Write text in a temporary folder and read it back.
- Catch a specific exception and continue the program.

By the end
- Create a report and trigger FileExistsError with a second attempt at the same path.
- Use the original text read from the file as evidence that it was preserved.

Where you can use it
Keep last week’s digest safe when someone tries to save a new report under the same filename.

Generate the text first so it can be tested. Open the output path with x mode to protect a file of the same name. Practice with a temporary directory. A FileExistsError is a successful protection when the job is accidentally repeated.

Predict
What happens if you call open("x") on that same path again?
- FileExistsError is raised.
- The earlier report is overwritten.

Worked example (example.py)

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    report = Path(folder) / "weekly.txt"
    with report.open("x", encoding="utf-8") as file:
        file.write("Garden: 10")
    print(report.read_text(encoding="utf-8"))


Example result
Garden: 10

Write Garden: 10 and attempt to write Changed to the same path with x. Catch FileExistsError and print Report already exists., then print the original file contents.

Starter program (starter.py)

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    report = Path(folder) / "weekly.txt"
    with report.open("x", encoding="utf-8") as file:
        file.write("Garden: 10")
    print(report.read_text(encoding="utf-8"))


Hint
Put the second write in try. Read the report after the exception handler.

Case 1. Try the sample
Input
(No input.)
Expected output
Report already exists.
Garden: 10

Stretch
Run the test with a different file path and explain what a safe scheduled job would do after a name conflict.

Reflect
What proves that the second run preserved the first report?

Check your prediction
FileExistsError is raised. Exclusive creation protects an existing file.
