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
# Reading, line by line
with open("marks.txt", "r") as f:
for line in f:
print(line.strip()) # strip removes the newline character
# Writing — REPLACES everything already there
with open("report.txt", "w") as f:
f.write("Class report\n")
# Appending — keeps what was there
with open("log.txt", "a") as f:
f.write("Ana logged in\n")// Reading, line by line
BufferedReader in = new BufferedReader(new FileReader("marks.txt"));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line.trim());
}
in.close(); // close it yourself
// Writing — REPLACES everything already there
FileWriter out = new FileWriter("report.txt");
out.write("Class report\n");
out.close();
// Appending — keeps what was there (the true is what makes it append)
FileWriter log = new FileWriter("log.txt", true);
log.write("Ana logged in\n");
log.close();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
A line read from a file carries the invisible newline character that ended it.
So "Ana" compared against a line reading "Ana\n" is not equal. Use strip() to remove it before comparing.
Everything read is text
A line reading "72" is the string "72", not the number 72.
Convert with int() before doing arithmetic, and be ready for a line that will not convert.
Write a newline yourself
write adds nothing of its own, so consecutive writes run together on one line.
End each with \n unless you deliberately want them joined.
Close it, always
An unclosed file may not have its contents fully written to disk, and it holds a system resource.
with handles this; without it, the close belongs in a finally block.
total = 0
count = 0
try:
with open("marks.txt", "r") as f:
for line in f:
line = line.strip() # remove the newline
if line != "": # skip any blank line
total = total + int(line)
count = count + 1
except FileNotFoundError:
print("marks.txt was not found.")
except ValueError:
print("A line in marks.txt was not a number.")
if count > 0:
print("Average:", total / count)int total = 0;
int count = 0;
try {
BufferedReader in = new BufferedReader(new FileReader("marks.txt"));
String line;
while ((line = in.readLine()) != null) {
line = line.trim();
if (!line.equals("")) { // skip any blank line
total = total + Integer.parseInt(line);
count = count + 1;
}
}
in.close();
} catch (FileNotFoundException e) {
System.out.println("marks.txt was not found.");
} catch (NumberFormatException e) {
System.out.println("A line in marks.txt was not a number.");
} catch (IOException e) {
System.out.println("Could not read marks.txt.");
}
if (count > 0) {
System.out.println("Average: " + (double) total / count);
}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 answer broken into clear points, with guidance on how each point earns marks.