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?
- Hint 1: What happens to the variables of a program when it stops running?
- Hint 2: Where could data be put so that it is still there tomorrow?
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?
- Hint 1: Think of lists that are long, or that other programs also use.
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
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.
- Hint 1: Think of a notebook: what do you do before writing, and after?
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"Follow each file command and see what it does to scores.txt.
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.
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.
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.
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
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?
- Hint 1: The stages are the same three as for writing, with a different mode.
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| Statement | Name | Score |
|---|---|---|
| OPENFILE "scores.txt" FOR READ | ||
| READFILE "scores.txt", Name | ||
| READFILE "scores.txt", Score | Maya | |
| CLOSEFILE "scores.txt" | Maya | 17 |
| OUTPUT Name, " scored ", Score | Maya | 17 |
Show the completed table
| Statement | Name | Score |
|---|---|---|
| OPENFILE "scores.txt" FOR READ | ||
| READFILE "scores.txt", Name | Maya | |
| READFILE "scores.txt", Score | Maya | 17 |
| CLOSEFILE "scores.txt" | Maya | 17 |
| OUTPUT Name, " scored ", Score | Maya | 17 |
The program outputs: Maya scored 17
Check your understanding
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.
- Hint 1: Think about what OPENFILE … FOR WRITE does to a file that already exists.
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
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?
- Hint 1: The program knows how many lines there are.
- Hint 2: Think about the totalling method from Lesson 6.
- Declare, and set the total to 0 first.
Total ← 0goes before the loop, as in Lesson 6, so that it is not reset on each pass. - Open the file once, before the loop, for reading. Opening it inside the loop would start again at the first line every time.
- Read one line on each pass.
READFILEtakes the next line, so five passes read the five marks in order. The marks go into a variable, and each is added toTotal. - Close the file after the loop. The program has finished with the file only when the last line has been read.
- 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| Position | Mark read from the file | Total after the pass |
|---|---|---|
| 1 | 12 | 12 |
| 2 | 7 | |
| 3 | 15 | |
| 4 | 9 | |
| 5 | 13 |
Show the completed table
| Position | Mark read from the file | Total after the pass |
|---|---|---|
| 1 | 12 | 12 |
| 2 | 7 | 19 |
| 3 | 15 | 34 |
| 4 | 9 | 43 |
| 5 | 13 | 56 |
The program outputs: Total: 56
Check your understanding
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.
Work this out on paper or the board first. Nothing here is marked: compare yours with the model answer.
- Hint 1: Open the file for writing before the loop and close it after.
- Hint 2: Use a FOR loop, because the number of names is known.
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
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", ScoreApply it
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
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, asFOR WRITEandFOR 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 noCLOSEFILEto forget.writedoes not add the end of a line by itself, so"\n"is added.readlineincludes it, so.strip()removes it.- Everything read from a text file is text:
int(…)turns the line17into a number. Writing a number needsstr(…)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 READorFOR WRITE, thenREADFILEorWRITEFILE, thenCLOSEFILE. READFILEtakes the next line into a variable;WRITEFILEwrites a variable’s value as a line.- Opening a file
FOR WRITEreplaces 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).
A sequence of precise steps that solves a problem or completes a task.
A fixed-size structure that stores several values of the same data type under one name, each found by its index.
A loop that repeats a fixed number of times, known before it starts. In pseudocode it is a FOR … NEXT loop.
An organised collection of data stored so that it can be searched, sorted and updated.
A named collection of data kept on secondary storage, so that it is still there when the program stops and the computer is switched off.
A precise but language-independent way of writing an algorithm, with set keywords such as IF, WHILE and OUTPUT, that is not tied to any one programming language.
A high-level programming language written as text, popular for learning and for real work, in which indentation shows which lines belong together.
Storage that the CPU cannot access directly, used to keep programs and data permanently, such as a hard disk drive or a solid-state drive.
A file that stores its data as lines of readable text, so that it can be opened in any simple text editor.
Memory that loses its contents when the power is switched off.
Your progress on this lesson
Saved in this browser only. It is not sent anywhere, does not follow you to another device, and is lost if you clear this site’s data.
This browser is not allowing the site to save progress, so it will be forgotten when you leave the page.