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.
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
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.
Decide whether the file should be read, overwritten or appended before choosing the file mode. Use sample data to check parsing and consider what happens if a file does not exist.
Quick check: What is the key difference between modes "w" and "a"?
Check: "w" writes from the beginning and normally truncates an existing file; "a" appends to its end.