aımnova
DashboardMy LearningCrash CoursesStudy Plan

Aimnova site navigation

Stay in the loop

Get the latest study resources and updates

New features, study tips and exam insights — straight to your inbox.

IB Diploma

  • IB Past Papers
  • IB Study Notes
  • IB Question Bank
  • IB Mock Exams
  • IB Revision

IB Subjects

  • IB Math AA
  • IB Math AI
  • IB Economics
  • IB Business Management
  • IB Physics
  • IB Biology
  • View all IB subjects→

IB Past Papers

  • IB Math AA HL Past Papers
  • IB Math AA SL Past Papers
  • IB Math AI HL Past Papers
  • IB Math AI SL Past Papers
  • IB Economics HL Past Papers
  • IB Economics SL Past Papers
  • IB ESS Past Papers
  • View all past papers→

Study Resources

  • Study Notes
  • Question Bank
  • Mock Exams
  • Crash Courses
  • Flashcards
  • Revision Guide
  • Exam Skills
  • Command Terms
  • Grade Calculator
  • Exam Timetable 2026

Aimnova

  • Features
  • Pricing
  • For Teachers
  • For Schools
  • For Parents
  • About Us
  • Blog
  • Contact
aımnova

IB study, practice and feedback built around the real exam.

TermsPrivacyCookies·© 2026 Aimnova. All rights reserved.c1e448f

Aimnova is not affiliated with or endorsed by the International Baccalaureate Organization (IB).

NotesComputer Science HLTopic 6.5File processing
Back to Computer Science HL Topics
6.5.15 min read

File processing (Computer Science HL)

IB Computer Science · Unit 6

Exam preparation

Practice the questions examiners actually ask

Our question bank mirrors real IB exam papers. Practice under timed conditions and track your progress across topics.

Start Practicing

Contents

  1. 1Data that outlives the program
  2. 2The three modes
  3. 3Reading, and getting it wrong
  4. 4Exam-style question
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.
Start Studying Free Full access to Aimnova Pro · cancel anytime

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.

Get Exam Ready FreeYour first topic is free to keep • No credit card required
1

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.

2

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.

3

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.

4

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.
IB-style questionConstruct[6 marks]

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.

Claim your free topic

Try an IB Exam Question — Free AI Feedback

Test yourself on File processing. Write your answer and get instant AI feedback — just like a real IB examiner.

the size of a file holding 5000 records of 120 bytes each, in megabytes. Take 1 MB as 1 000 000 bytes. [2 marks]

Related Computer Science HL Topics

Continue learning with these related topics from the same unit:

6.1.1Variables and data types6.1.2Substrings6.1.3Exception handling6.1.4Debugging
View all Computer Science HL topics
Improve your exam techniqueCommand terms, paper structure, and mark-scheme tips for Computer Science HL
Previous6.4.5Tracing recursionNextFundamentals of OOP7.1.1

25 questions to test your understanding

Reading is just the start. Students who tested themselves scored 82% on average — try IB-style questions with AI feedback.

Start FreeView All Computer Science HL Topics