Study Guide

File Handling

Why a program stores data in a file, and how to open, read, write and close a text file in Cambridge pseudocode, including what writing does to the data already in the file, with the same ideas in Python.

Lesson 5.15 Algorithms and Programming

For: Cambridge IGCSE Computer Science learners, or Key Stage 3 learners who can write loops and use variables (about ages 13 to 14)

Stage: Think

A scoreboard that forgets

A fictional quiz app at Riverside School shows the top score of the week. A pupil beats the record, the app proudly shows the new score, and the app is closed. The next morning, when it is opened again, the record has gone and the board is empty.

Think it through

The program stored the top score in a variable. Why had it forgotten the score by the next day? What would the program need so that it remembers between one run and the next?

Show a model answer

A variable lives in the computer’s main memory while the program runs, and it disappears when the program stops. To remember the score, the program has to put it somewhere that keeps data when the program is closed and the computer is switched off, such as a file on a storage device, and read it back the next time it starts.

Stage: Discover

Why programs use files

Think it through

Apart from remembering a high score, give two other things a program might need to keep, or to be given, in a file. Think about a school: what data would you not want to type in again every time?

Show a model answer

For example: a list of pupils’ names and form groups, that would take a long time to type in every time; a day’s attendance, kept so that the office can look at it later; settings such as a pupil’s chosen colours; marks that a teacher entered last week and wants to use again.

A file is a named collection of data kept on secondary storage, such as a hard disk or a solid-state drive, so that it is still there when the program stops and the computer is switched off. The variables of a program are held in the computer’s main memory, which is volatile memory: it loses its contents when the power goes off, and a program’s variables are lost when it ends. A file does not lose its contents in that way.

A program uses a file when it needs to:

  • keep data between one run and the next;
  • use more data than a person would want to type in each time;
  • share data with other programs or people, or move it from one computer to another.

This lesson uses text files: files that store their data as lines of readable text, which you could open in any simple text editor. In the model used in this lesson, each item the program writes goes on its own line.

Check your understanding

A quiz program must still know the top score the next day. Why is a variable not enough?
Show the answer

Answer: C. A variable is held in main memory, which is cleared at the end.

A file keeps data after the program ends; a variable does not.

Stage: Predict

Writing data to a file

The quiz app wants to save the name of the top scorer, Maya, and her score of 17, in a file called scores.txt.

Think it through

Before a program can put data into a file, what do you think it must tell the computer first? And what should it do when it has finished? Put the three stages in order.

Show a model answer

First it must say which file it wants to use and what it will do with it (write to it, in this case). Then it puts the data in. When it has finished, it must say that it is done with the file, so the computer can finish storing the data. The order is: open, write, close.

In Cambridge pseudocode the stages have three commands. OPENFILE names the file and the mode: FOR WRITE means data will be written. WRITEFILE puts one item of data into the file. CLOSEFILE says the program has finished with the file.

DECLARE Name : STRING
DECLARE Score : INTEGER
Name ← "Maya"
Score ← 17
OPENFILE "scores.txt" FOR WRITE
WRITEFILE "scores.txt", Name
WRITEFILE "scores.txt", Score
CLOSEFILE "scores.txt"
What happens as the writing program runs

Follow each file command and see what it does to scores.txt.

  1. Program

    Step 1 of 4: OPENFILE "scores.txt" FOR WRITE

    The file is opened for writing. If it already holds data, that data is lost, and the file starts empty.

  2. Program

    Step 2 of 4: WRITEFILE "scores.txt", Name

    The value of Name, Maya, is written as the first line of the file.

    Technical detail: The file now holds one line: Maya.

  3. Program

    Step 3 of 4: WRITEFILE "scores.txt", Score

    The value of Score, 17, is written as the next line.

    Technical detail: The file now holds two lines: Maya, then 17.

  4. Program

    Step 4 of 4: CLOSEFILE "scores.txt"

    The program has finished with the file, so it is closed and its data is safely stored.

The commands use the variables’ names, but the file receives their values.

Check your understanding

After the program has run, what does scores.txt contain?
Show the answer

Answer: A. Two lines: Maya on the first and 17 on the second.

The file holds values, not variable names.

Stage: Discover

Reading data from a file

Tomorrow the quiz app starts again. The file scores.txt holds two lines: Maya, then 17.

Think it through

Using what you know about writing, what would the three stages of reading be, and how would the program get Maya into a variable called Name and 17 into a variable called Score?

Show a model answer

The stages are again open, use and close, with the file opened for reading. Instead of putting a variable’s value into the file, the program takes a line from the file and puts it into a variable: first line into Name, second line into Score.

To read, the file is opened FOR READ. Each READFILE takes the next line from the file and assigns it to the variable named, and the first READFILE reads the first line.

DECLARE Name : STRING
DECLARE Score : INTEGER
OPENFILE "scores.txt" FOR READ
READFILE "scores.txt", Name
READFILE "scores.txt", Score
CLOSEFILE "scores.txt"
OUTPUT Name, " scored ", Score
Following the reading program
StatementNameScore
OPENFILE "scores.txt" FOR READ
READFILE "scores.txt", Name
READFILE "scores.txt", ScoreMaya
CLOSEFILE "scores.txt"Maya17
OUTPUT Name, " scored ", ScoreMaya17

    Show the completed table
    StatementNameScore
    OPENFILE "scores.txt" FOR READ
    READFILE "scores.txt", NameMaya
    READFILE "scores.txt", ScoreMaya17
    CLOSEFILE "scores.txt"Maya17
    OUTPUT Name, " scored ", ScoreMaya17

    The program outputs: Maya scored 17

    Check your understanding

    If the two READFILE lines were swapped, so that Score was read first, what would happen?
    Show the answer

    Answer: B. Score would receive Maya, the first line, and Name would receive 17.

    Lines are read in the order they are stored.

    Stage: Predict

    What writing does to old data

    The next week, Omar beats the record with a score of 20. The program is run again, the same way as before, with Name as Omar and Score as 20: it opens scores.txt FOR WRITE, writes the two values and closes the file.

    Think it through

    Predict what scores.txt holds when the program has finished. Does Maya’s line stay in the file? Give a reason.

    Show a model answer

    It holds two lines: Omar and 20. Maya’s line is gone. Opening a file FOR WRITE starts it afresh: any data already in the file is lost, and the new data is written in its place.

    Opening a file FOR WRITE does not add to what is already there: it replaces it. The syllabus’s pseudocode guide says that a new file will be created and any existing data in the file will be lost. If a program has to keep the old data as well as the new, it must first read the old data into variables (or an array), close the file, then open it FOR WRITE and write the old data and the new data together. A file should be open in only one mode at a time, so the file is closed after reading and before writing.

    Check your understanding

    The writing program is run for Maya (17), and later for Omar (20), with no other changes. A reading program then runs READFILE into Name. What does Name hold?
    Show the answer

    Answer: D. Omar, because the second run replaced the first.

    Writing replaces; it does not add to what is there.

    Stage: Explain

    Reading several lines with a loop

    The file five.txt holds a teacher’s five marks, one on each line: 12, 7, 15, 9 and 13. The teacher wants the total without typing the marks again.

    Think it through

    Which kind of loop would you use to read the five lines, and why? Where would you put the line that sets the total to 0?

    Show a model answer

    A FOR loop, because the number of lines is known to be five. The total is set to 0 before the loop, as in every totalling algorithm, so that it is not reset on each pass.

    1. Declare, and set the total to 0 first. Total ← 0 goes before the loop, as in Lesson 6, so that it is not reset on each pass.
    2. Open the file once, before the loop, for reading. Opening it inside the loop would start again at the first line every time.
    3. Read one line on each pass. READFILE takes the next line, so five passes read the five marks in order. The marks go into a variable, and each is added to Total.
    4. Close the file after the loop. The program has finished with the file only when the last line has been read.
    5. Output the result after the loop, once every mark has been added.
    DECLARE Mark : INTEGER
    DECLARE Total : INTEGER
    Total ← 0
    OPENFILE "five.txt" FOR READ
    FOR Position ← 1 TO 5
      READFILE "five.txt", Mark
      Total ← Total + Mark
    NEXT Position
    CLOSEFILE "five.txt"
    OUTPUT "Total: ", Total
    Following the file-reading loop
    PositionMark read from the fileTotal after the pass
    11212
    27
    315
    49
    513

      Show the completed table
      PositionMark read from the fileTotal after the pass
      11212
      2719
      31534
      4943
      51356

      The program outputs: Total: 56

      Check your understanding

      Why is CLOSEFILE placed after the loop rather than inside it?
      Show the answer

      Answer: C. Closing inside the loop would shut the file before the next READFILE.

      Open once before the loop, close once after it.

      Go deeper When the number of lines is not known

      The syllabus’s pseudocode guide for this course reads a known number of lines, as above. A program that does not know how many lines a file has needs a way to ask whether the end has been reached. A Level pseudocode has a function EOF(FileName), true when no data is left to read, used like this:

      Total ← 0
      OPENFILE "five.txt" FOR READ
      WHILE NOT EOF("five.txt") DO
        READFILE "five.txt", Mark
        Total ← Total + Mark
      ENDWHILE
      CLOSEFILE "five.txt"

      For the same file the loop runs five times and the total is again 56. This is an extension beyond the IGCSE guide, so questions at IGCSE tell you how many lines to read.

      Stage: Apply

      Write a program that uses a file

      Think it through

      Write pseudocode that asks for the names of three players, one at a time, and writes each name on its own line in a file called team.txt.

      Show a model answer
      DECLARE PlayerName : STRING
      OPENFILE "team.txt" FOR WRITE
      FOR Count ← 1 TO 3
        OUTPUT "Enter the name of player ", Count
        INPUT PlayerName
        WRITEFILE "team.txt", PlayerName
      NEXT Count
      CLOSEFILE "team.txt"

      The file is opened once before the loop and closed once after it, and each name is written as soon as it is typed. Because the file is opened FOR WRITE, any earlier team list is replaced.

      A program contains these lines:

      OPENFILE "scores.txt" FOR READ
      WRITEFILE "scores.txt", Score
      CLOSEFILE "scores.txt"

      Apply it

      What is wrong with the three lines of this program?
      Show the answer

      Answer: D. The file is open FOR READ, so WRITEFILE cannot write to it.

      Check that the mode matches what the program does.

      A pupil wants a program to read the saved score from scores.txt, so the program starts like this:

      OPENFILE "scores.txt" FOR WRITE
      READFILE "scores.txt", Score

      Apply it

      What is the result of running these two lines on a file that holds a saved score?
      Show the answer

      Answer: A. The old contents are lost when the file is opened, so nothing is read.

      Open the file for the job the program is about to do.

      Stage: Consolidate

      Show what you know

      Think it through

      Explain to a friend why the quiz app needs a file to remember the top score, and describe the three stages and the commands for each when the app saves a score. Say what would happen to the old score.

      Show a model answer

      A good answer says that variables are lost when the program ends because main memory is volatile, but a file on secondary storage keeps its data. Saving a score takes three stages: open the file for writing (OPENFILE … FOR WRITE), write the data (WRITEFILE) and close the file (CLOSEFILE). Opening for writing replaces the old contents, so the old top score would be lost unless the program had read it first.

      Apply it

      A teacher’s program must add a new pupil’s result to a file that already holds earlier results, without losing them. Which approach is correct using the commands in this lesson?
      Show the answer

      Answer: B. Read the old results first, close the file, then write old and new together.

      To keep old data, read it first and write it again with the new data.

      Go deeper The same ideas in Python
      name = "Maya"
      score = 17
      with open("scores.txt", "w") as file:
          file.write(name + "\n")
          file.write(str(score) + "\n")
      
      with open("scores.txt", "r") as file:
          name = file.readline().strip()
          score = int(file.readline().strip())
      print(name, "scored", score)

      This prints Maya scored 17.

      • open(name, "w") opens for writing and "r" for reading, as FOR WRITE and FOR READ. Mode "w" replaces the old contents, as in the pseudocode.
      • with … as file: closes the file for you when its block ends, so there is no CLOSEFILE to forget.
      • write does not add the end of a line by itself, so "\n" is added. readline includes it, so .strip() removes it.
      • Everything read from a text file is text: int(…) turns the line 17 into a number. Writing a number needs str(…) to turn it into text.
      • To read all the lines when you do not know how many there are, for line in file: goes through every line until the end.
      • A file keeps data on secondary storage, so it survives when the program ends; variables in volatile main memory do not.
      • Use three stages: OPENFILE name FOR READ or FOR WRITE, then READFILE or WRITEFILE, then CLOSEFILE.
      • READFILE takes the next line into a variable; WRITEFILE writes a variable’s value as a line.
      • Opening a file FOR WRITE replaces what it held. Read the old data first if it must be kept.
      • A file is open in one mode at a time. Open it before the loop and close it after.

      Sources and scope

      • What this lesson is. The fifteenth lesson of the Algorithms and Programming module, written for this site. It covers point 8.3 of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6) and the file handling commands of its pseudocode guide. Its curriculum links are provisional and imply no review or endorsement by any examination board.
      • Original material. The Riverside School quiz app, Maya, Omar and the teacher’s marks are fictional, written for this lesson. The pseudocode follows the layout in the syllabus’s pseudocode guide, and each trace and output was worked out by hand; the Python was run.
      • Simplified on purpose. Each item is treated as one line of a text file. Reading until the end of a file is not part of the IGCSE guide, so the lesson’s programs read a known number of lines, and the end-of-file test is shown only as an A Level extension. Appending to a file, and file organisation, are not taught.
      • Left to other lessons. Using files in a whole scenario (Lesson 16) and databases (a later module).