The big idea: Variables disappear when the program ends. A file does not.
Working with one always follows the same three steps: open, use, close.
The mode is chosen when you open it: r read · w write · a append.
And w empties the file immediately, before you write anything. Choosing w when you meant a destroys everything that was there.
Free preview
This is the free notes preview
You're reading the free notes. Aimnova Pro unlocks the full study experience — and you can try it with your first topic free to keep:
- FlashcardsLock in vocabulary and key terms with spaced repetition.
- Practice questionsAnswer exam-style questions and get instant AI marking.
- Mock exams & past-paper vaultSit full mocks and see exactly how examiners award marks.
- Personalised study planA daily plan built around your exam date and weak areas.
r — read
- Reads what is there; cannot write
- Fails if the file does not exist
- The safe default: it cannot damage anything
w — write
- Empties the file at once, then writes
- Creates it if it does not exist
- Right only when replacing the contents entirely
- The destructive one — be certain before using it
a — append
- Adds at the end, keeping what was there
- Creates it if it does not exist
- Right for logs, records and anything accumulating
with closes it for you: Opening a file inside a with block closes it automatically when the block ends — even if something goes wrong inside.
That is the finally block from exception handling, built into the language.
Feeling unprepared for exams?
Get a clear study plan, practice with real questions, and know exactly where you stand before exam day. No more guessing.
Every line ends with a newline
Everything read is text
Write a newline yourself
Close it, always
How this is tested — you must choose the right mode and handle the file actually failing. It comes up two ways:
Paper 2 — working with code
- Construct code to read, write or append, 4-6 marks
- Explain the difference between the modes
- Say why a file must be closed
Paper 2 — the algorithmic-thinking question
- Reason about file handling with no code shown
- Explain what would go wrong with the wrong mode
The classic trap: Opening in w when you meant a. The file is emptied the moment it opens, before a single line is written — and the previous contents are gone with no warning.
A program must add today's attendance to a running log, then report how many days are recorded. Write it, handling the file being missing.
Model answer plan
See the mark-by-mark plan — for / against / judgement, with marking guidance — in study mode.