FH

8.3 File Handling

Text files • reading • writing • appending • CIE pseudocode • Python

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

TermSimple definition
File handlingProgramming techniques used to work with information stored in text files.
Text fileA 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 fileThe point where there is no more data to read.
End-of-file flagA Boolean variable used to record whether the end of the file has been reached.
READFILECIE pseudocode command for reading file data.
WRITEFILECIE pseudocode command for writing file data.
OPENFILECIE pseudocode command for opening a file.
CLOSEFILECIE pseudocode command for closing a file.
TRIMRemoves 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

OperationCIE pseudocodePython
OpenOPENFILE "fruit.txt" FOR READfile = open("fruit.txt", "r")
CloseCLOSEFILE "fruit.txt"file.close()
Read lineREADFILE "fruit.txt", LineOfTextfile.readline()
Write lineOPENFILE "fruit.txt" FOR WRITE
WRITEFILE "fruit.txt", "Oranges"
file.write("Oranges")
AppendNot a Cambridge file mode in the official pseudocode guide.file = open("shopping.txt", "a")
Real-life example:A school program can store student or attendance information in a text file and retrieve it later.

Activity 1A: Identify the operation

Classroom / homework activity

Match: get existing data, add new data, finish using a file, start using a file.

TaskAnswer
Get existing dataRead
Add new dataWrite / Append
FinishClose
Start usingOpen

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

  • 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.
  • Opening text files.
  • Reading text files.
  • Writing text files.
  • Closing text files.
  • 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.
  • 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.
  • 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
Original sample loaded.

2. Reading Data from Text Files

The source reading example usesemployees.txt. Each employee is stored as four lines: name, department, salary and age.

EmployeeNameDepartmentSalaryAge
GregGregSales3900043
LucyLucyHuman resources2675028
JordanJordanPayroll4500031

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.
CIE pseudocode
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"
Python
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()
Visualisation:Think of a reading pointer moving down the text file. Four lines form one employee record. An empty name signals that no more records remain.

Activity 2A: Trace Greg

Classroom / homework activity

Which four values are read for Greg?

FieldValue
NameGreg
DepartmentSales
Salary39000
Age43

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

  • The program needs existing data.
  • Python uses mode r for reading.
  • The pseudocode uses FOR READ.
  • The data can then be processed or displayed.
  • 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.
  • 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.
  • 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.
  • 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.

CIE pseudocode
OPENFILE "employees.txt" FOR WRITE
WRITEFILE "employees.txt", "Polly"
WRITEFILE "employees.txt", "Sales"
WRITEFILE "employees.txt", "26000"
WRITEFILE "employees.txt", "32"
CLOSEFILE "employees.txt"
Python
file = open("employees.txt", "a")
file.write("Polly\n")
file.write("Sales\n")
file.write("26000\n")
file.write("32\n")
file.close()
Python modeMeaningImportant point
rRead onlyUse to read existing data.
wWriteCreates a file if needed; an existing file is overwritten.
aAppendWrites at the end of an existing file.
Real-life example:Adding a new attendance record should keep previous attendance records. That is the kind of task demonstrated by append mode.

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.

Solution
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

  • 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.
  • 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.
  • 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.
  • It adds data after existing contents.
  • Existing records are kept.
  • The new record is placed at the end.
  • This matches the Polly example.
  • 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.

CIE pseudocode structures
OPENFILE <File identifier> FOR <File mode>
READFILE <File Identifier>, <Variable>
WRITEFILE <File identifier>, <Variable>
CLOSEFILE <File identifier>
CIE pseudocode — copy one line
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

Stages 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.

Solution
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

  • OPENFILE is the command.
  • It includes the file identifier.
  • A file mode follows it.
  • Examples include FOR READ, FOR WRITE and FOR APPEND.
  • 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.
  • WRITEFILE writes to a file.
  • It identifies the target file.
  • It supplies the data.
  • The source uses it when storing employee fields.
  • Open the file.
  • Write the data.
  • Close the file.
  • The stages form the basic file-writing sequence.
  • 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 useOPENFILE ... 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.

PurposeHow the source describes it
PersistenceData can be kept and used again later.
SharingStored information can be shared/used by programs or users.
BackupA stored copy of information can be kept.
ConfigurationFiles can hold configuration information.
Large datasetsFiles can handle large amounts of stored data.
LoggingFiles can keep records of activity.
Input/outputFiles support data input and output operations.
SerializationData can be stored for later retrieval.
Database interactionFile storage contributes to data-management and database-related use.
Python — store then retrieve
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.

Real-life example:An application can store user data in a file and load it again when needed, rather than requiring the user to enter it every time.

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.

PurposeUse
BackupKeep a stored copy
LoggingKeep records of activity
ConfigurationStore program settings/information
Large datasetsStore substantial amounts of data

Check Your Understanding

  • 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.
  • 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.
  • 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.
  • 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.
  • 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

ModeMeaningRemember
rRead onlyRead existing data.
wWriteExisting file contents are overwritten.
aAppendAdd 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.

CIE pseudocode model
INPUT Title
INPUT Year
OPENFILE "books.txt" FOR WRITE
WRITEFILE "books.txt", Title
WRITEFILE "books.txt", Year
CLOSEFILE "books.txt"
Mark pointRequired action
1Input the title.
2Input the year / open the required file mode.
3Write the data to the file.
4Close 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

  • 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.
  • Input the required data.
  • Open the file in the correct mode.
  • Write the data.
  • Close the file.
  • 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.
  • 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.
  • 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 questionFile-handling operations represented
calculate, close, count, createclose, create
output, print, read, sortread
test, total, writewrite

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.

Model answer
DECLARE Mark : STRING
OPENFILE "marks.txt" FOR READ
READFILE "marks.txt", Mark
OUTPUT Mark
CLOSEFILE "marks.txt"

Check Your Understanding

  • read is the file operation.
  • READFILE is the CIE command.
  • The program reads stored data.
  • The source practice question includes read.
  • 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.
  • Open the file for reading.
  • Read the data.
  • Process or output the data.
  • Close the file.
  • 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

  • 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.
  • 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.
  • 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.
  • Input the required data.
  • Open the correct file mode.
  • Write the required data.
  • Close the file.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.