🎯 Syllabus & Goals 3 min
Cambridge 8.3 · File handling Paper 2 · Algorithms, Programming and Logic
By the end of this lesson you can:
- Explain why programs store data in files.
- Open a file for
READorWRITE, read or write one line or one item of data, and close it — in pseudocode and Python. - Write a short algorithm that keeps data between runs of a program by using a file.
Textbook: Chapter 8, §8.3 (pp. 333–336)
Recap / Warm-Up 5 min
Last lesson: arrays hold many values under one name. But every variable and array lives in RAM while the program runs.
Quick starter
A game stores its high score in a variable. The player closes the game and restarts it. What is the high score now — and why? (Think back to Unit 3.)
Reveal the answer
It is lost. RAM is volatile: its contents disappear when the program ends or the power goes off. To keep the score, the program must save it to a file on secondary storage.
🧠 Key Concept 14 min
1 · Why store data in a file?
- Data in RAM is lost when the computer is switched off; data saved to a file is stored permanently.
- The same program can use the data again later, e.g. the next time it runs.
- Another program can open and use the data.
- The file can be sent to other computers.
2 · Using a file — open, read or write, close
Every file is identified by its filename. For IGCSE you read and write one line of text or a single item of data.
| Step | Pseudocode | Python |
|---|---|---|
| Open to write (replaces any old contents) | OPENFILE "Data.txt" FOR WRITE | f = open("Data.txt", "w") |
| Write a line / item | WRITEFILE "Data.txt", TextLine | f.write(text_line) |
| Open to read | OPENFILE "Data.txt" FOR READ | f = open("Data.txt", "r") |
| Read a line / item into a variable | READFILE "Data.txt", TextLine | text_line = f.readline() |
| Close the file | CLOSEFILE "Data.txt" | f.close() |
Worked Example 12 min
Example 1 · Write a line of text, then read it back
Cambridge pseudocode
DECLARE TextLine : STRING DECLARE MyFile : STRING MyFile ← "Message.txt" // write the line of text to the file OPENFILE MyFile FOR WRITE OUTPUT "Please enter a line of text: " INPUT TextLine WRITEFILE MyFile, TextLine CLOSEFILE MyFile // read the line of text back from the file OUTPUT "The file contains this line of text:" OPENFILE MyFile FOR READ READFILE MyFile, TextLine OUTPUT TextLine CLOSEFILE MyFile
The same in Python
# Write one line of text to a file, then read it back my_file = open("Message.txt", "w") # open for WRITE text_line = input("Please enter a line of text: ") my_file.write(text_line) # write the line my_file.close() # close the file print("The file contains this line of text:") my_file = open("Message.txt", "r") # open for READ text_line = my_file.readline() # read one line print(text_line) my_file.close()
Please enter a line of text: Meet at the library at 4pm The file contains this line of text: Meet at the library at 4pm
- The filename is stored in a variable,
MyFile.if the name changes, only one line is edited. - Open for WRITE → write → close.closing makes sure the text is actually saved to storage.
- Open again, this time for READ, and read into
TextLine.a file is opened in one mode at a time.
Example 2 · Keeping a high score between games
The file HighScore.txt holds one integer. Read it, compare it with this game's score, and save the new score if it is higher.
Cambridge pseudocode
DECLARE HighScore, NewScore : INTEGER
OPENFILE "HighScore.txt" FOR READ
READFILE "HighScore.txt", HighScore
CLOSEFILE "HighScore.txt"
OUTPUT "Current high score: ", HighScore
OUTPUT "Your score this game: "
INPUT NewScore
IF NewScore > HighScore
THEN
OPENFILE "HighScore.txt" FOR WRITE
WRITEFILE "HighScore.txt", NewScore
CLOSEFILE "HighScore.txt"
OUTPUT "New high score saved!"
ELSE
OUTPUT "No new high score"
ENDIFThe same in Python
# Keep the high score in a file so it survives after the program ends score_file = open("HighScore.txt", "r") high_score = int(score_file.readline()) # read one item, cast to INTEGER score_file.close() print("Current high score:", high_score) new_score = int(input("Your score this game: ")) if new_score > high_score: score_file = open("HighScore.txt", "w") score_file.write(str(new_score)) # files store text, so cast back score_file.close() print("New high score saved!") else: print("No new high score")
Output — two separate runs (the file started with 250)
Current high score: 250 Your score this game: 310 New high score saved! Current high score: 310 Your score this game: 200 No new high score
| Run | File before | HighScore | NewScore | NewScore > HighScore? | File after |
|---|---|---|---|---|---|
| 1 | 250 | 250 | 310 | TRUE | 310 |
| 2 | 310 | 310 | 200 | FALSE | 310 |
The second run "remembers" 310 — even though every variable was wiped when the first run ended. That is the whole point of a file.
Try It Yourself 12 min
Goal: The file Motto.txt stores one line of text. Write pseudocode and Python to display it.
Goal: Input a user's name and favourite colour. Write the name to Name.txt and the colour to Colour.txt. Then read both back and output "Alex likes blue".
Goal: Write an algorithm that copies a line of text from one text file (Source.txt) to another (Copy.txt), converting it to upper case on the way. Add comments to explain each step.
Hint
Two files are involved, so you need two OPENFILE statements with different modes, one READFILE, one WRITEFILE and two CLOSEFILE statements. Use UCASE between the read and the write.
📝 Exam Practice 10 min
Explain why a program might store data in a file.
Mark scheme
- Data in RAM / variables is lost when the program ends / the computer is switched off; a file stores it permanently (1).
- So the data can be used again later / by another program / sent to another computer (1).
A computer file, "Message.txt", stores a line of text. Write an algorithm in pseudocode to display this line of text.
Mark scheme
OPENFILE "Message.txt" FOR READ(1)READFILE "Message.txt", TextLinethenOUTPUT TextLine(1)CLOSEFILE "Message.txt"(1)
Write pseudocode to input a student's name and store it in the file "Students.txt", replacing anything already in the file.
Mark scheme
- Prompt and
INPUT StudentName(1). OPENFILE "Students.txt" FOR WRITE(1).WRITEFILE "Students.txt", StudentName(1).CLOSEFILE "Students.txt"(1).
State the two file modes used with OPENFILE for IGCSE, and what each allows.
Mark scheme
READ— data can be read from the file (1).WRITE— data can be written to the file / replaces the existing contents (1).
🗝️ Recap & Key Terms 3 min
Files keep data after a program ends. Always open (in READ or WRITE mode), read or write one line or item, then close. WRITE replaces the old contents. In Python, remember that files hold text: cast with int() after reading and str() before writing a number.
- File
- A collection of data stored by a computer program to be used again.
- OPENFILE
- Makes a file available to the program in a given mode (READ or WRITE).
- READFILE
- Reads a line of text / an item of data from an open file into a variable.
- WRITEFILE
- Writes a line of text / an item of data to a file opened for writing.
- CLOSEFILE
- Closes the file so the data is saved and the file is released.
Homework 1 min
Task (≤ 15 min): Write pseudocode that reads a number from "Visits.txt", adds 1 to it, outputs "You have visited n times", and writes the new number back to the file. [5]
Model answer
DECLARE Visits : INTEGER // read the old count OPENFILE "Visits.txt" FOR READ READFILE "Visits.txt", Visits CLOSEFILE "Visits.txt" // update and report it Visits ← Visits + 1 OUTPUT "You have visited ", Visits, " times" // save the new count OPENFILE "Visits.txt" FOR WRITE WRITEFILE "Visits.txt", Visits CLOSEFILE "Visits.txt"
Marks: open for READ and read into a variable (1); close after reading (1); add 1 and output (1); open for WRITE and write (1); close after writing (1).