GCSE Python · Lesson 7 of 9

Text files and exception handling

OCR J277 2.2 / AQA 8525 programming

Write results to a file, then read and total the values safely.

← All GCSE Python lessons

Robust file processing

Programs can write and read text files to preserve simple records. They also need to anticipate missing files and invalid contents. Test both the expected file and an error case so that the program fails gracefully.

Watch out: Catching every exception without explaining the problem can conceal bugs. Catch the specific errors you expect.

1 · Learn and predict

Read this worked example. Predict its output, run it in Python 3, and explain how variables change.

from pathlib import Path
path = Path('sample_scores.txt')
path.write_text('12\n15\n18\n', encoding='utf-8')
print(path.read_text(encoding='utf-8'))

2 · Build independently

Write results to a file, then read and total the values safely. Work from the starter code before comparing with the solution.

Download starter + solution ZIP ↓

For a stretch challenge: add meaningful test data, handle an edge case and explain one design decision.

Reveal reference solution
from pathlib import Path
path = Path('sample_scores.txt')
path.write_text('12\n15\n18\n', encoding='utf-8')
try:
    with path.open('r', encoding='utf-8') as f:
        lines = f.readlines()
    values = [int(line.strip()) for line in lines if line.strip()]
    print('Total:', sum(values))
except (OSError, ValueError) as exc:
    print('Could not process file:', exc)

The reference is one possible approach. Test your own program before comparing.

3 · Debug and explain

Question: Why use with open(...) instead of leaving a file open?

Show explanation

The context manager closes the file reliably even if an exception happens.

4 · Check your understanding

Why handle ValueError?

5 · Reflect

Explain one test you used, one problem you solved and one improvement you would make.

This records completion only in this browser and does not certify mastery.

Want extra practice? Try interactive Python tracing and debugging questions →