All subjects · Computer Science · WCP02 Practical Programming and Problem-solving
Text files: open, read, write, append and close
Edexcel IAL Computer Science · WCP02 Practical Programming and Problem-solving
Programs keep data between runs by saving it to files. Unit 2 tasks read data files and write formatted results to new files.
Opening and closing (spec 8.2.3)
open(filename, mode) returns a file object. Modes: "r" read (the file must exist), "w" write (creates the file or erases an existing one), "a" append (adds to the end). Always close() the file so the data is saved and the file is released.
f = open("scores.txt", "w")
f.write("Ana,72\n")
f.write("Ben,64\n")
f.close()
f = open("scores.txt", "a")
f.writelines(["Cai,81\n", "Dee,59\n"])
f.close()
f = open("scores.txt", "r")
print(f.read())
f.close()Output:
Ana,72
Ben,64
Cai,81
Dee,59write() does not add a new line for you: include "\n". writelines() writes a list of strings.
Reading line by line
Loop over the file, or use readline() (one line) or readlines() (a list of all lines). Each line ends with "\n", so strip() it, then split(",") for comma-separated fields. Values read from a file are strings.
f = open("scores.txt", "r")
total = 0
count = 0
for line in f:
fields = line.strip().split(",")
total = total + int(fields[1])
count = count + 1
f.close()
print(count, total / count)Output:
4 69.0Loading into a structure
A common pattern is to read a file into a 2D list of records, process the list, then write results:
f = open("scores.txt", "r")
records = []
for line in f.readlines():
name, mark = line.strip().split(",")
records.append([name, int(mark)])
f.close()
out = open("passes.txt", "w")
for r in records:
if r[1] >= 60:
out.write(f"{r[0]:<5}{r[1]:>4}\n")
out.close()
print(open("passes.txt").read())Output:
Ana 72
Ben 64
Cai 81Errors with files
Opening a missing file in "r" mode raises FileNotFoundError; catch it with try/except. Control characters: "\n" line feed, "\r" carriage return, "\t" tab.
Worked example
A file has three lines: 5, 8 and 2. Write code to display their total.
- f = open("nums.txt", "r")
- total = 0; for line in f: total = total + int(line.strip())
- f.close(); print(total)
- Result: 15
Answer: 15
Check yourself
- What is displayed when this code runs?
```python
f = open("log.txt", "w")
f.write("first\n")
f.close()
f = open("log.txt", "w")
f.write("second\n")
f.close()
f = open("log.txt", "r")
print(len(f.readlines()))
f.close()
```
Show answer
1. Opening in "w" mode erases the file, so only 'second' remains: 1 line.
- What is displayed when this code runs?
```python
f = open("log.txt", "w")
f.write("first\n")
f.close()
f = open("log.txt", "a")
f.write("second\n")
f.close()
f = open("log.txt", "r")
print(len(f.readlines()))
f.close()
```
Show answer
2. "a" adds to the end, so the file now has 2 lines.
- What is displayed when this code runs?
```python
f = open("data.txt", "w")
f.write("alpha\nbeta\ngamma\n")
f.close()
f = open("data.txt", "r")
f.readline()
print(f.readline().strip())
f.close()
```
Show answer
beta. The first readline() reads 'alpha'; the second reads the next line: beta.
- What is displayed when this code runs?
```python
f = open("people.txt", "w")
f.write("Zoe,15\nYan,18\nXia,17\n")
f.close()
f = open("people.txt", "r")
oldest = ""
best = 0
for line in f:
name, age = line.strip().split(",")
if int(age) > best:
best = int(age)
oldest = name
f.close()
print(oldest)
```
Show answer
Yan. Each age is converted to int and compared; the oldest is Yan.
- Which exception is raised when this code runs?
```python
f = open("no_such_file.txt", "r")
```
- NameError
- KeyError
- EOFError
- FileNotFoundError
Show answer
FileNotFoundError. Reading a file that does not exist raises FileNotFoundError.
- What is displayed when this code runs?
```python
f = open("t.txt", "w")
f.write("A")
f.write("B")
f.close()
print(open("t.txt").read())
```
- A / B
- AB
- A B
- BA
Show answer
AB. write() adds no new line, so the file holds AB.
- This code should total the numbers stored one per line in nums.txt (10, 20, 30). Which line completes it?
```python
f = open("nums.txt", "w")
f.write("10\n20\n30\n")
f.close()
f = open("nums.txt", "r")
total = 0
for line in f:
__________
f.close()
print(total)
```
- `total = total + line`
- `total = total + line.strip()`
- `total = int(line)`
- `total = total + int(line.strip())`
Show answer
`total = total + int(line.strip())`. Lines are strings ending in \n, so strip and convert before adding.
Sources
- Pearson Edexcel International Advanced Subsidiary/Advanced Level in Computer Science specification (XCP01/YCP01), first teaching 2026
- Pearson IAL Computer Science Unit 2 Programming Language Subset (PLS), Python 3
- Pearson IAL Computer Science IAS sample assessment materials (Unit 2 paper and mark scheme)
Last updated 8 November 2026. Spotted a mistake? Tell us.