Learning Objectives
- explain the purpose of storing data in text files
- open, read, write and close text files
- use CIE pseudocode OPENFILE, READFILE, WRITEFILE and CLOSEFILE
- use Python file modes r, w and a
- read single lines and groups of related lines from a file
- write single items and lines of text to a file
- use an end-of-file flag in a file-reading loop
- apply file handling to exam-style problems
- explain persistence, sharing, backup, configuration, large datasets, logging, input/output, serialization and database interaction as purposes of file storage
Key Terms
| Term | Simple definition |
|---|---|
| File handling | Programming techniques used to work with information stored in text files. |
| Text file | A file used to store text data. |
| Read mode (r) | Python mode used to read a file. |
| Write mode (w) | Python mode used to write; an existing file is overwritten. |
| Append mode (a) | Python mode used to add data to the end of a file. |
| End of file | The point where there is no more data to read. |
| End-of-file flag | A Boolean variable used to record whether the end of the file has been reached. |
| READFILE | CIE pseudocode command for reading file data. |
| WRITEFILE | CIE pseudocode command for writing file data. |
| OPENFILE | CIE pseudocode command for opening a file. |
| CLOSEFILE | CIE pseudocode command for closing a file. |
| TRIM | Removes extra spaces/newlines from text in the source example. |
| readline() | Python method used in the notes to read one line from a text file. |
1. File Handling — Open, Read, Write, Close
File handling is the use of programming techniques to work with information stored in text files.
- opening text files
- reading text files
- writing text files
- closing text files
Core operations
| Operation | CIE pseudocode | Python |
|---|---|---|
| Open | OPENFILE "fruit.txt" FOR READ | file = open("fruit.txt", "r") |
| Close | CLOSEFILE "fruit.txt" | file.close() |
| Read line | READFILE "fruit.txt", LineOfText | file.readline() |
| Write line | OPENFILE "fruit.txt" FOR WRITE WRITEFILE "fruit.txt", "Oranges" | file.write("Oranges") |
| Append | Not a Cambridge file mode in the official pseudocode guide. | file = open("shopping.txt", "a") |
Activity 1A: Identify the operation
Classroom / homework activity
Match: get existing data, add new data, finish using a file, start using a file.
| Task | Answer |
|---|---|
| Get existing data | Read |
| Add new data | Write / Append |
| Finish | Close |
| Start using | Open |
Activity 1B: Choose the Python mode
Classroom / homework activity
A program only needs to read an existing file.
ris correct because the notes say "r" is for reading from a file only.
Check Your Understanding
1. What is file handling?
- It is working with information stored in text files.
- It includes opening files.
- It includes reading and writing data.
- It includes closing files when they are no longer needed.
2. Name the four core file-handling techniques.
- Opening text files.
- Reading text files.
- Writing text files.
- Closing text files.
3. What does reading a file mean?
- The program obtains information already stored in the file.
- The information is processed by the program.
- The Python example uses read mode.
- The pseudocode example uses READFILE.
4. What does writing a file mean?
- The program puts data into the file.
- The data can be a single item or a line.
- The Python example uses write operations.
- The CIE example uses WRITEFILE.
5. Why must a file be closed?
- The source examples close files after use.
- CIE pseudocode uses CLOSEFILE.
- Python examples use file.close().
- It completes the file-handling sequence.
Interactive File Simulator
Greg Sales 39000 43 Lucy Human resources 26750 28 Jordan Payroll 45000 31
2. Reading Data from Text Files
The source reading example usesemployees.txt. Each employee is stored as four lines: name, department, salary and age.
| Employee | Name | Department | Salary | Age |
|---|---|---|---|---|
| Greg | Greg | Sales | 39000 | 43 |
| Lucy | Lucy | Human resources | 26750 | 28 |
| Jordan | Jordan | Payroll | 45000 | 31 |
Step-by-step
- Step 1 — open the file for reading.
- Step 2 — set endOfFile to FALSE.
- Step 3 — while the flag is FALSE, read the employee fields.
- Use TRIM after reading each line to remove extra spaces/newlines.
- Step 4 — if name is empty, set the end-of-file flag; otherwise output the record.
- Step 5 — close the file.
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"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()Activity 2A: Trace Greg
Classroom / homework activity
Which four values are read for Greg?
| Field | Value |
|---|---|
| Name | Greg |
| Department | Sales |
| Salary | 39000 |
| Age | 43 |
Activity 2B: Explain the EOF flag
Classroom / homework activity
Why is endOfFile initially FALSE?
- The loop needs a starting state.
- The program should continue while the end has not been reached.
- The flag changes to TRUE when the empty name is detected.
- This provides the stopping condition.
Check Your Understanding
6. Why is the file opened in read mode?
- The program needs existing data.
- Python uses mode r for reading.
- The pseudocode uses FOR READ.
- The data can then be processed or displayed.
7. Why is TRIM used after reading a line?
- It removes extra spaces/newlines.
- The source applies it to each field.
- It makes the text cleaner before output.
- It is part of the reading example.
8. What happens when name = ""?
- The program treats this as the end of the file.
- endOfFile is set to TRUE.
- The empty record is not output.
- The loop stops afterwards.
9. Why are four READFILE operations used per employee?
- The sample record has four fields.
- The fields are name, department, salary and age.
- Each field is stored on its own line.
- Reading four lines reconstructs one employee record.
10. What is the purpose of the WHILE loop?
- It repeats the reading process.
- It continues while the EOF flag is FALSE.
- It allows multiple records to be processed.
- It stops when the EOF condition is reached.
3. Writing New Data and Appending
The Python example appends a new employee, Polly, to the existing file. Forstrict Cambridge IGCSE pseudocode, however, the official guide lists onlyREADandWRITEas file modes. Therefore, do not writeFOR APPENDin a Cambridge pseudocode answer.
OPENFILE "employees.txt" FOR WRITE
WRITEFILE "employees.txt", "Polly"
WRITEFILE "employees.txt", "Sales"
WRITEFILE "employees.txt", "26000"
WRITEFILE "employees.txt", "32"
CLOSEFILE "employees.txt"file = open("employees.txt", "a")
file.write("Polly\n")
file.write("Sales\n")
file.write("26000\n")
file.write("32\n")
file.close()| Python mode | Meaning | Important point |
|---|---|---|
| r | Read only | Use to read existing data. |
| w | Write | Creates a file if needed; an existing file is overwritten. |
| a | Append | Writes at the end of an existing file. |
Important:Python supports"a"for append mode, as shown in the source notes. This is aPython feature. The Cambridge pseudocode guide supplied for examinations from 2026 does not define APPEND as a pseudocode file mode.
Activity 3A: Pick the correct mode
Classroom / homework activity
You need to add a new student to an existing file without replacing the old students.
a— append mode.
Activity 3B: Append Polly
Classroom / homework activity
Write Python to append Polly, Sales, 26000 and 32 as four lines.
file = open("employees.txt", "a")
file.write("Polly\n")
file.write("Sales\n")
file.write("26000\n")
file.write("32\n")
file.close()Check Your Understanding
11. What is append mode?
- It is Python mode a.
- It writes at the end of an existing file.
- It keeps the old contents.
- The source uses it to add Polly.
12. What is the danger of write mode?
- Mode w is used for writing.
- If the same file exists, its contents are overwritten.
- Old data can therefore be lost.
- A backup is recommended by the notes.
13. Why are newline characters used in the Python example?
- Each employee field is stored on a separate line.
- \n moves the next field to the next line.
- This preserves the four-line record structure.
- It matches the reading algorithm.
14. Why is append suitable for adding a new record?
- It adds data after existing contents.
- Existing records are kept.
- The new record is placed at the end.
- This matches the Polly example.
15. What should you remember before using w?
- Check whether existing contents must be preserved.
- w can overwrite an existing file.
- Do not use it accidentally when adding records.
- Use backups when working with important text files.
4. Cambridge IGCSE Pseudocode for File Handling
Use the following Cambridge IGCSE forms for pseudocode questions.
OPENFILE <File identifier> FOR <File mode>
READFILE <File Identifier>, <Variable>
WRITEFILE <File identifier>, <Variable>
CLOSEFILE <File identifier>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.txtStages of writing
- Open the file for creating, overwriting or appending.
- Write the data to the file.
- Close the file.
Stages of reading
- Open the file for reading.
- Set a Boolean variable to FALSE to show the end has not been reached.
- While the end-of-file flag is FALSE and the search item has not been found, read data.
- If the data matches the item being searched for, assign the data as required.
- Check for the end of the file and set the flag when reached.
- Close the file.
Activity 4A: Copy one line
Classroom / homework activity
Write CIE pseudocode to copy a line from FileA.txt to FileB.txt.
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"Activity 4B: Find the missing stage
Classroom / homework activity
An algorithm opens and writes a file but does not finish the file operation.
Close the fileusing CLOSEFILE.
Check Your Understanding
16. Which CIE command opens a file?
- OPENFILE is the command.
- It includes the file identifier.
- A file mode follows it.
- Examples include FOR READ, FOR WRITE and FOR APPEND.
17. Which CIE command reads a value?
- READFILE reads from a file.
- It identifies the file.
- It supplies a variable to receive the value.
- The source uses it for each employee field.
18. Which CIE command writes a value?
- WRITEFILE writes to a file.
- It identifies the target file.
- It supplies the data.
- The source uses it when storing employee fields.
19. What are the three stages of writing?
- Open the file.
- Write the data.
- Close the file.
- The stages form the basic file-writing sequence.
20. Why should Python syntax not be copied into a CIE pseudocode answer?
- The source provides separate CIE pseudocode structures.
- Pseudocode should use OPENFILE, READFILE, WRITEFILE and CLOSEFILE.
- Python uses open(), readline(), write() and close().
- Using the required form makes the intended file operation clear.
Official Cambridge Pseudocode Check
- The Cambridge guide for examinations from 2026 explicitly defines the file modes asREADandWRITE.
- APPEND is not listed as a Cambridge pseudocode file mode, so students should not use
OPENFILE ... FOR APPENDin a CIE pseudocode answer. - WRITEcreates a new file and, if a file already exists with the same name, the existing data is lost.
- UseOPENFILE,READFILE,WRITEFILEandCLOSEFILEexactly in the Cambridge form.
- Cambridge's guide shows file names such as"FileA.txt"and"FileB.txt"as the file identifiers.
5. Why Store Data in a File?
The source explains that file storage allows programs to store and retrieve data and supports several important purposes.
| Purpose | How the source describes it |
|---|---|
| Persistence | Data can be kept and used again later. |
| Sharing | Stored information can be shared/used by programs or users. |
| Backup | A stored copy of information can be kept. |
| Configuration | Files can hold configuration information. |
| Large datasets | Files can handle large amounts of stored data. |
| Logging | Files can keep records of activity. |
| Input/output | Files support data input and output operations. |
| Serialization | Data can be stored for later retrieval. |
| Database interaction | File storage contributes to data-management and database-related use. |
data_to_store = ["Noureddine", "Tadjirout", 35, "Noureddine"]
file_path = "user_data.txt"
with open(file_path, "w") as file:
for data in data_to_store:
file.write(str(data) + "\n")
retrieved_data = []
with open(file_path, "r") as file:
for line in file:
retrieved_data.append(line.strip())
print("Data retrieved from the file:", retrieved_data)The source walkthrough writes every item indata_to_storetouser_data.txt, reopens it in read mode, reads each line intoretrieved_data, and displays the result.
Activity 5A: Explain persistence
Classroom / homework activity
Explain why a file can keep data available after a program has finished running.
- The data is stored in the file.
- The file remains available after that program run.
- The program can open and read the data later.
- The notes identify persistence as a key purpose.
Activity 5B: Match the purpose
Classroom / homework activity
Match backup, logging, configuration and large datasets to the correct use.
| Purpose | Use |
|---|---|
| Backup | Keep a stored copy |
| Logging | Keep records of activity |
| Configuration | Store program settings/information |
| Large datasets | Store substantial amounts of data |
Check Your Understanding
21. What does persistence mean here?
- Data is kept in a file.
- It can be used again later.
- It is not limited to one program run.
- Persistence is one purpose listed in the notes.
22. Give two purposes of storing data in files.
- Persistence is one possible purpose.
- Backup is another possible purpose.
- The notes also include sharing, configuration, logging and large datasets.
- The purpose depends on what the stored information is needed for.
23. How can files support backups?
- A file can hold a stored copy.
- The copy can be kept for recovery.
- Backup is listed as a purpose of file storage.
- This helps preserve stored information.
24. What happens in the source store-and-retrieve example?
- The list data_to_store is written to user_data.txt.
- The same file is opened for reading.
- Lines are placed into retrieved_data.
- The retrieved data is displayed.
25. Why are files useful for large datasets?
- Large amounts of information can be stored.
- The data can be read when needed.
- Large datasets are explicitly named as a purpose.
- This supports flexible data management.
6. Exam Tips, File Modes and Worked Example
Python file modes
| Mode | Meaning | Remember |
|---|---|---|
| r | Read only | Read existing data. |
| w | Write | Existing file contents are overwritten. |
| a | Append | Add data to the end while keeping existing contents. |
Exam tips from the notes
- Use the correct letter in the open command.
- r is for reading.
- w is for writing and may overwrite.
- a is for writing to the end of an existing file.
- Always make a backup of text files you are working with.
Worked Example — store a book title and year
The source worked example asks for a book title and year and stores them inbooks.txt. The Cambridge guide doesnotdefine an APPEND file mode, so the strict Cambridge pseudocode version usesFOR WRITE. Remember that Cambridge states that WRITE causes any existing data in that file to be lost.
INPUT Title
INPUT Year
OPENFILE "books.txt" FOR WRITE
WRITEFILE "books.txt", Title
WRITEFILE "books.txt", Year
CLOSEFILE "books.txt"| Mark point | Required action |
|---|---|
| 1 | Input the title. |
| 2 | Input the year / open the required file mode. |
| 3 | Write the data to the file. |
| 4 | Close the file. |
Activity 6A: Fix the file mode
Classroom / homework activity
A student uses Python w mode to add a record while keeping old records.
Use"a"instead. The notes state that"w"overwrites an existing file and"a"writes to the end.
Activity 6B: Four-mark discipline
Classroom / homework activity
For a 4-mark file-writing algorithm, state four clear marking points.
- Take the required input.
- Open the correct file in the appropriate mode.
- Write the required data.
- Close the file.
Check Your Understanding
26. What is the difference between w and a?
- w opens the file for writing and can overwrite old contents.
- a adds data to the end of an existing file.
- a preserves the old contents.
- Choose between them according to the task.
27. What four stages should appear in a basic write-file solution?
- Input the required data.
- Open the file in the correct mode.
- Write the data.
- Close the file.
28. Why is the correct mode important in an exam?
- The mode controls the type of file operation.
- w can overwrite contents.
- a keeps old contents and adds new data.
- r is for reading only.
29. Why is a backup recommended?
- The source warns that a mistake can lose contents.
- This is especially important when working with w mode.
- A backup keeps a copy of the data.
- The notes explicitly recommend backups.
30. What is the main exam structure to remember?
- Open the file.
- Read or write the required data.
- Process/output it as required.
- Close the file.
7. Past Paper Practice — Recognising File Operations
The TED notes include a Paper 2 practice question asking students to identify file-handling operations from a list of words.
| Words in the practice question | File-handling operations represented |
|---|---|
| calculate, close, count, create | close, create |
| output, print, read, sort | read |
| test, total, write | write |
Activity 7A: File-handling word hunt
Classroom / homework activity
From calculate, close, count, create, output, print, read, sort, test, total, write, select the file-handling operations.
close, create, read, write.
Activity 7B: Mini exam question
Classroom / homework activity
Write CIE pseudocode to open marks.txt for reading, read one line into Mark, output it and close the file.
DECLARE Mark : STRING
OPENFILE "marks.txt" FOR READ
READFILE "marks.txt", Mark
OUTPUT Mark
CLOSEFILE "marks.txt"Check Your Understanding
31. Which word clearly represents a file-reading operation?
- read is the file operation.
- READFILE is the CIE command.
- The program reads stored data.
- The source practice question includes read.
32. Why is it useful to recognise individual operations?
- Exams may ask for a specific file action.
- Knowing the action helps construct an algorithm.
- It helps choose the correct CIE command.
- This supports short Paper 2 questions.
33. What should a basic read-file algorithm contain?
- Open the file for reading.
- Read the data.
- Process or output the data.
- Close the file.
34. What should a basic write-file algorithm contain?
- Open the file in the required mode.
- Write the data.
- Preserve the intended file behaviour.
- Close the file.
Key Takeaways
- File handling works with information stored in text files.
- Core operations: open, read, write, close.
- Python: r = read, w = write/overwrite, a = append.
- CIE pseudocode: OPENFILE, READFILE, WRITEFILE, CLOSEFILE.
- Read loops can use an end-of-file Boolean flag.
- TRIM removes extra spaces/newlines in the supplied example.
- The employee example stores four lines per record.
- Append keeps existing contents and adds new data at the end.
- Write mode can overwrite an existing file.
- File storage supports persistence, sharing, backup, configuration, large datasets, logging, input/output, serialization and database interaction.
- Exam solutions should follow the requested language and file mode.
- Close files when finished and back up important text files.
Question Bank
1. Explain why data is stored in files. [5 marks]
- Files store data for later use.
- They provide persistence.
- They can support sharing and backups.
- They can store configuration, logging and large datasets.
- They make program data management more flexible.
2. Explain r, w and a in Python. [4 marks]
- r reads an existing file.
- w writes and can overwrite an existing file.
- a appends to an existing file.
- The mode must match the task.
3. Describe the employee-reading algorithm. [5 marks]
- Open employees.txt for reading and set endOfFile to FALSE.
- Use a WHILE loop while the end has not been reached.
- Read name, department, salary and age and use TRIM.
- If name is empty set the EOF flag; otherwise output the fields.
- Close the file after the loop.
4. Give four marking points for a basic file-writing algorithm. [4 marks]
- Input the required data.
- Open the correct file mode.
- Write the required data.
- Close the file.
5. Explain the difference between a text file and a program variable for stored data. [4 marks]
- A file holds information in persistent storage.
- A variable holds data for the running program.
- A file can be opened again later.
- The notes identify persistence as a main reason for file storage.
6. Write CIE pseudocode to copy one line from FileA.txt to FileB.txt. [5 marks]
- Declare a STRING variable for the line.
- Open FileA.txt for READ.
- Open FileB.txt for WRITE.
- Read from FileA and write the value to FileB.
- Close both files.
7. Explain why the end-of-file flag is needed in the reading example. [4 marks]
- It records whether the end of the file has been reached.
- It starts as FALSE.
- It changes to TRUE when the empty name is found.
- The WHILE loop uses it to stop reading.
8. Explain why append mode is suitable for the Polly employee example. [5 marks]
- Polly is a new record.
- Existing employees must remain.
- Append writes to the end of the file.
- Write mode could overwrite existing contents.
- The source example therefore uses append.
9. Describe four maintainable exam habits for file handling. [4 marks]
- Use the correct file mode.
- Use the correct CIE pseudocode commands when pseudocode is requested.
- Include clear input/output statements where needed.
- Close the file after processing.
10. A student wants to store a book title and year in books.txt. Explain a correct solution structure. [5 marks]
- Input the title.
- Input the year.
- Open books.txt in a mode suitable for the task.
- Write the title and year to the file.
- Close the file.