Library Computer Science 0478 File Handling
O Level · Computer Science 0478

File Handling

Revise File Handling for Computer Science 0478 (O Level) — revision notes and instant AI marking. Free to start.

📖 Revision notes · preview
Cambridge (CIE) IGCSE · Computer Science

File Handling

Big idea: A program can permanently save information by opening a text file, writing or reading lines of text one at a time, and then closing it again — exactly like opening a notebook, writing a sentence, and closing the notebook so nothing gets lost.

Summary — What This Chapter Covers

  • Why we need file handling: variables disappear when a program ends — files let data survive after the program closes.
  • The four core operations: open, read, write, close — every file-handling task is built from these.
  • Three file modes: read ("r"), write ("w"), and append ("a") — each behaves very differently.
  • Reading data: using a loop with an "end of file" flag to read every line until there's nothing left.
  • Writing data: sending new lines into a file, and the difference between overwriting and adding on.
  • Pseudocode vs Python syntax: how the same idea is written in exam pseudocode and in real Python code.
  • Common mistakes: forgetting to close a file, using the wrong mode, and not stripping newline characters.

1. What Is File Handling?

Think about a variable in your program — say name = "Greg". The moment your program finishes running, that variable is wiped from memory. It's gone forever. That's fine for temporary calculations, but what if you're building a school system that needs to remember 500 students' names, even after you close the program and switch off the computer overnight?

That's exactly the problem file handling solves. It's the set of programming techniques used to work with information stored in text files — files that live on the hard disk (not in temporary memory/RAM), so they survive after the program ends, the computer restarts, or even years later.

There are four techniques you need to master, and almost every file-handling question is just some combination of these:

  • Opening a text file — telling the program "I want to work with this file now"
  • Reading a text file — pulling data out of the file into your program
  • Writing a text file — pushing data from your program into the file
  • Closing a text file — telling the program "I'm finished, save everything and let go of the file"
Analogy A text file is like a notebook. Opening it is picking it up off the shelf. Reading is running your eyes down the lines. Writing is picking up a pen and adding text. Closing is putting the notebook back on the shelf so the words are safely stored — if you walk away without closing it, pages might get lost or smudged (i.e. data might not actually get saved).

2. The Core Commands — Pseudocode vs Python

Cambridge exams use their own pseudocode style for file handling, which looks a little different from real Python — but they represent the exact same underlying actions. You need to be fluent in both because a question might ask you to write pseudocode, or trace/complete actual Python code.

ConceptPseudocode (exam style)Python
OpenOPENFILE "fruit.txt" FOR READfile = open("fruit.txt","r")
CloseCLOSEFILE "fruit.txt"file.close()
Read lineREADFILE "fruit.txt", LineOfTextfile.readline()
Write lineOPENFILE "fruit.txt" FOR WRITE
WRITEFILE "fruit.txt", "Oranges"
file = open("fruit.txt","w")
file.write("Oranges")
AppendOPENFILE "fruit.txt" FOR APPENDfile = open("fruit.txt","a")
Golden Rule Every single file you open must be closed once you're done with it. Skipping CLOSEFILE / file.close() is one of the most common ways students lose marks — the exam board treats it as an incomplete algorithm, and in real programs it can mean your data never actually gets saved to disk.
Practice Question 1 Write the single Python line of code needed to open a file called "scores.txt" so that you can add new results to the end of it, without deleting what's already there.
Practice Question 2 In exam pseudocode, write the command to close a file called "employees.txt".

3. The Three File Modes — Read, Write, Append

This is the part students get wrong most often in exams, so let's slow right down. When you open a file, you must tell the computer what you intend to do with it. There are three modes, and each one behaves completely differently if the file already contains data:

"r" — Read mode

Use this when you only want to look at the contents of a file — you're not changing anything. The file must already exist; if it doesn't, the program will crash with an error.

"w" — Write mode

This is the mode that catches people out. "w" mode does two very different things depending on the situation:

  • If the file does not exist yet, it creates a brand new file.
  • If the file already exists, it deletes everything inside it and starts completely empty. This is called overwriting.
Danger Zone Opening an existing file in "w" mode by mistake will silently wipe out everything that was in it — with no warning, no "are you sure?" popup. This is a genuinely common real-world mistake, and exams love testing whether you understand the consequence.

"a" — Append mode

This is the safe way to add new data to an existing file. It opens the file, moves straight to the very end, and any new writes get tacked on after the existing content — nothing gets deleted.

Quick Reference "r" = read only, file must exist  |  "w" = write, creates OR wipes  |  "a" = write, adds to the end safely
Practice Question A student has a file called "highscores.txt" already containing 20 saved scores. They run file = open("highscores.txt", "w") and then write one new score before closing the file. How many scores will the file contain afterwards, and why?

4. Reading Data — Looping Until the End of the File

Here's a problem: when you write a program to read a file, you often don't know in advance how many lines it contains. It might be 4 lines today and 4,000 lines after the school adds more students next term. So you can't just write "read line 1, read line 2, read line 3" — you need a loop that keeps reading until there's nothing left to read.

The standard technique is an end-of-file flag: a boolean variable that starts as FALSE and flips to TRUE the moment the program detects it has run out of data (usually because readline() returns an empty string, meaning there was nothing left to read).

Worked Example — reading employee records

Imagine employees.txt stores four pieces of data per person, each on its own line: name, department, salary, age. So for three employees the file looks like this:

Greg
Sales
39000
43
Lucy
Human resources
26750
28
Jordan
Payroll
45000
31

To read this, we loop round four READFILE calls at a time (one per field), and check after reading the name whether it came back empty — that's our signal the file has ended:

// Pseudocode
OPENFILE "employees.txt" FOR READ
endOfFile ← FALSE

WHILE NOT endOfFile DO
   READFILE "employees.txt", name
   name ← TRIM(name)
   READFILE "employees.txt", department
   department ← TRIM(department)
   READFILE "employees.txt", salary
   salary ← TRIM(salary)
   READFILE "employees.txt", age
   age ← TRIM(age)

   IF name = "" THEN
      endOfFile ← TRUE
   ELSE
      OUTPUT "Name: " & name
      OUTPUT "Department: " & department
      OUTPUT "Salary: " & salary
      OUTPUT "Age: " & age
      OUTPUT ""
   ENDIF
ENDWHILE

CLOSEFILE "employees.txt"

And the equivalent, fully working Python:

# Python
file = open("employees.txt", "r")
endOfFile = False

while not endOfFile:
    name = file.readline().strip()
    department = file.readline().strip()
    salary = file.readline().strip()
    age = file.readline().strip()

    if name == "":
        endOfFile = True
    else:
        print("Name: ", name)
        print("Department: ", department)
        print("Salary: ", salary)
        print("Age: ", age)
        print()

file.close()
Why TRIM / .strip() matters Every line in a text file secretly ends with an invisible "newline" character (like pressing Enter). If you don't remove it, comparisons like name == "" will never come true even at the real end of the file, and printed output will have odd extra blank lines. TRIM() in pseudocode and .strip() in Python both remove this invisible character along with any extra spaces.
Practice Question Why do we check IF name = "" to detect the end of the file, rather than checking the salary or age fields?

5. Writing New Data to a File

Writing follows the same shape as reading, just in reverse: open the file (in "w" or "a" mode), write out each piece of data, then close it. One subtlety: in pseudocode, writing a NEWLINE is a separate, explicit command — you have to manually tell the file to start a new line after each value, otherwise everything gets squashed onto one line.

Worked Example — appending a new employee

// Pseudocode
OPENFILE "employees.txt" FOR APPEND

WRITEFILE "employees.txt", "Polly"
WRITEFILE "employees.txt", NEWLINE
WRITEFILE "employees.txt", "Sales"
WRITEFILE "employees.txt", NEWLINE
WRITEFILE "employees.txt", "26000"
WRITEFILE "employees.txt", NEWLINE
WRITEFILE "employees.txt", "32"
WRITEFILE "employees.txt", NEWLINE

CLOSEFILE "employees.txt"

In Python, there's no separate "write newline" command — you simply include \n directly inside the string you're writing:

# Python
file = open("employees.txt", "a")

file.write("Polly\n")
file.write("Sales\n")
file.write("26000\n")
file.write("32\n")

file.close()

After running either version, the file now has a fourth record tacked onto the end, with everything from before completely untouched:

Greg
Sales
39000
43
Lucy
Human resources
26750
28
Jordan
Payroll
45000
31
Polly
Sales
26000
32
Exam-style Question (4 marks) Use pseudocode to write an algorithm that: inputs the title and year of a book from the user, then permanently stores the book title and year to the existing text file books.txt.

What to Memorise

File Handling
Programming techniques used to open, read, write, and close data stored in text files, so it survives after the program ends.
"r" mode
Read only. File must already exist.
"w" mode
Write mode. Creates a new file, or completely wipes an existing one before writing.
"a" mode
Append mode. Adds new data to the end of an existing file without deleting anything.
End-of-file flag
A boolean variable (starts FALSE) used to control a reading loop, set to TRUE once an empty line signals there's no more data left.
TRIM() / .strip()
Removes invisible newline characters and extra spaces from a line that's just been read.
OPENFILE / CLOSEFILE
Exam pseudocode commands to open and close a file — Python equivalents are open() and .close().
READFILE / WRITEFILE
Exam pseudocode commands to read one line, or write one value to a file — Python equivalents are .readline() and .write().

Concepts Checklist

Exam Tips & Common Mistakes

Mode confusion Mixing up "w" and "a" is the #1 mistake. Ask yourself: "does this task want me to keep the old data or not?" If the question mentions adding to existing records, it's "a". If it's building a fresh file, it's "w".
Forgetting CLOSEFILE Examiners specifically award a mark for closing the file. Always finish your algorithm by closing every file you opened — treat it as a checklist step, not an optional extra.
Missing TRIM/.strip() If a mark scheme is testing reading loops, forgetting to remove the newline character is a classic way to lose marks, since your end-of-file check will never trigger correctly.
Backups Always back up a text file you're experimenting with. One accidental "w" mode open and your data is gone — this applies to real coding just as much as exam theory.
Reading the question mode Watch exam wording carefully — "permanently stores" doesn't automatically mean append; check whether existing data needs preserving before choosing "w" or "a".
NEWLINE in pseudocode Don't forget the explicit WRITEFILE "file.txt", NEWLINE command after each value in pseudocode — Python bundles this into \n inside the string instead, so the two styles look different even though they do the same job.
Revision guide generated from your File Handling chapter notes · Study offline, click any "Show Answer" button to reveal solutions.
🔓 Read the full File Handling note — free You're seeing the preview · free account, no card needed
Also in the full note
  • Exam Tips & Common Mistakes
What's inside
📖 Revision notes 🎯 Learn mode ✦ AI flashcards ✓ Instant AI marking 🧊 3D explorers 🧪 Experiments & simulations 📈 Progress tracking
📄 Practise File Handling with Computer Science 0478 past papers Every paper with its mark scheme — answer online, marked instantly. Open →

Read the full File Handling notes free

That's the preview — create a free account to read the rest, plus flashcards and practice questions with instant AI marking. No credit card.

Unlock the full notes free →

More Computer Science topics