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.

Practise this in the app: instant marking and a fix for every mistake. Free, no email needed to start.

Practise this lesson

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,59

write() 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.0

Loading 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    81

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

  1. f = open("nums.txt", "r")
  2. total = 0; for line in f: total = total + int(line.strip())
  3. f.close(); print(total)
  4. Result: 15

Answer: 15

Key idea: Modes: "r" read, "w" write (erases), "a" append; close() every file; lines end in \n and are strings, so strip(), split(",") and convert.

Check yourself

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

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

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

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

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

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

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

Practise with instant feedback

Sources

Last updated 8 November 2026. Spotted a mistake? Tell us.