8.3

Topic 8

File handling

  • IGCSE Computer science 0478
  • 2 min read
  • Syllabus 2026, 2027 and 2028

Objectives

  1. 1

    Understand the purpose of storing data in a file to be used by a program

  2. 2

    Open, close and use a file for reading and writing

Cambridge IGCSE Computer Science 0478 syllabus 2026-2028, 8.3 File handling (copied for internal use as permitted by Cambridge)

Detailed · Deep study

1Why store data in a file?

Variables and arrays are held in RAM, which is volatile, so their data is lost when the program ends. Writing the data to a file on secondary storage means it is stored permanently: it can be read the next time the program runs (e.g. high scores, settings, saved games), shared with other programs, or backed up.

Fig. 1Writing to and reading from a file.

2Opening, reading, writing and closing

CommandPurpose
OPENFILE <file> FOR READopens a file so data can be read from it
OPENFILE <file> FOR WRITEcreates a new file to write to; any existing data in it is lost
READFILE <file>, <variable>reads the next data item (or line of text) into the variable
WRITEFILE <file>, <variable>writes the data item (or line of text) into the file
CLOSEFILE <file>closes the file when it is no longer needed
DECLARE PlayerName : STRING
DECLARE Score : INTEGER
INPUT PlayerName
INPUT Score
OPENFILE "Scores.txt" FOR WRITE
WRITEFILE "Scores.txt", PlayerName
WRITEFILE "Scores.txt", Score
CLOSEFILE "Scores.txt"
Writing single items of data to a file. Opening for WRITE creates a new file and loses any existing data.
OPENFILE "Scores.txt" FOR READ
READFILE "Scores.txt", PlayerName
READFILE "Scores.txt", Score
CLOSEFILE "Scores.txt"
OUTPUT PlayerName, " scored ", Score
Reading the data back, in the same order it was written.
DECLARE LineOfText : STRING
OPENFILE "FileA.txt" FOR READ
OPENFILE "FileB.txt" FOR WRITE
READFILE "FileA.txt", LineOfText
WRITEFILE "FileB.txt", LineOfText
CLOSEFILE "FileA.txt"
CLOSEFILE "FileB.txt"
Copying a line of text from one file to another.
f = open("Scores.txt", "w")      # write mode
f.write("Ali\n")
f.write(str(25) + "\n")
f.close()

f = open("Scores.txt", "r")      # read mode
name = f.readline().strip()
score = int(f.readline())
f.close()
The same idea in Python.

3Exam focus

Key words: file; permanent storage; OPENFILE; READ; WRITE; READFILE; WRITEFILE; CLOSEFILE.

Quick self-check

Answer in your head first, then reveal.

  1. Data in variables is lost when the program closes (1); a file stores it permanently so it can be used again (1).

  2. OPENFILE "Notes.txt" FOR WRITE (1); WRITEFILE "Notes.txt", Message (1); CLOSEFILE "Notes.txt" (1).

  3. It is lost / overwritten (1).

Finished this subtopic? Track it on your subject page.