IB Computer Science B2.5: File processing
New IB Computer Science syllabus · first exams May 2027 · Theme B · Paper 2 · SL & HL · Python and Java
Programs often need to keep data after they close. B2.5 covers reading from and writing to text files, and choosing the right mode so you don't lose data by accident.
| Statement | Topic | Command term |
|---|---|---|
| B2.5.1 | File-processing operations | Construct |
Key points
Modes
- Read (
"r"): read an existing file. - Write (
"w"): erases the file as soon as it's opened, even if nothing is written, then writes from the start. - Append (
"a"): keeps the existing content and adds new data to the end.
Python
open(), read(), readline(), write(), close(). A with block closes the file automatically.
Java
Scanner or BufferedReader for reading, and FileWriter for writing. Use try-with-resources so the file is closed automatically.
Good practice
- Always close the file, or use
with/ try-with-resources. - Read large files line by line rather than loading the whole file into memory.
- Use
strip()/trim()to remove the newline at the end of each line.
Exam-style question
words.txt contains: cat, elephant, dog, butterfly, ant, crocodile (one per line). Construct code that reads every line and prints only the lines that contain more than 5 characters. [5]
Mark scheme
It prints elephant, butterfly, crocodile.
- [2] for correctly reading every line.
- [2] for the length check.
- [1] for correct output.
Python
file = open("words.txt", "r")
for line in file:
word = line.strip()
if len(word) > 5:
print(word)
file.close()Java
try (BufferedReader reader = new BufferedReader(new FileReader("words.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
String word = line.trim();
if (word.length() > 5) {
System.out.println(word);
}
}
} catch (IOException e) {
System.out.println("Could not read the file.");
}Common mistakes that cost marks
- Opening a file in
"w"mode to add data. That wipes the existing contents; use"a"instead. - Forgetting to strip the newline, so
"cat\n"counts as 4 characters, not 3. - Not closing the file, or not handling the case where it doesn't exist.
Frequently asked questions
Which file operations are on the syllabus?
Opening a sequential text file in read, write or append mode, then reading, writing, appending and closing it.
Which Java classes should I know?
The guide suggests Scanner, FileWriter and BufferedReader.
Go further
- Practise B2.5 with instant marking on ExamHaus, in Python or Java. → examhaus.com
- Full B2.5 presentation and question bank with mark scheme on CS Exam Ready. → csexamready.com/resources/ib-diploma
- IB CS mock exams: Paper 2 in Python and Java. → examhaus.com/mock-exams
