GCSE Computer Science

Python file handling โ€” GCSE Computer Science

Opening a file

Before Python can read or write a file, it needs to be opened with open(), which takes a filename and a mode.

file = open("scores.txt", "r")

The three modes GCSE exams expect

Reading a file

file = open("scores.txt", "r")
content = file.read()
print(content)
file.close()

.read() returns the whole file as a single string. .readlines() instead returns a list, one item per line โ€” useful when you need to process the file line by line rather than all at once.

file = open("scores.txt", "r")
lines = file.readlines()
for line in lines:
    print(line)
file.close()

Writing to a file

file = open("scores.txt", "w")
file.write("85\n")
file.write("92\n")
file.close()

Each call to .write() adds text to the file โ€” but because the file was opened in 'w' mode, anything that was in scores.txt before this code ran is gone the moment open() is called, not when .write() is.

Closing a file โ€” and the with open() pattern

Every file that gets opened should get closed โ€” leaving a file open can lose unsaved data or lock the file so other programs can't use it. Calling .close() explicitly works, but it's easy to forget, especially if an error happens before that line runs. The with open() pattern closes the file automatically, even if something goes wrong inside the block:

with open("scores.txt", "r") as file:
    content = file.read()
print(content)

GCSE exams increasingly expect with open() as the correct, safe way to write this code โ€” not open() and .close() written as two separate steps.

Common exam mistake

Using 'w' mode when the intention is to add to an existing file. Write mode overwrites โ€” the entire previous content is lost. Append mode ('a') is what's needed.

What examiners actually test

File handling questions typically give you a scenario โ€” reading scores from a file, appending a new record, overwriting a log โ€” and ask you to choose the correct mode and write the code to match. The 'w' vs 'a' distinction catches the most marks: read the scenario carefully to work out whether existing data is meant to survive.

Reading and writing files properly needs a real filesystem to test against โ€” which is exactly the kind of setup Python Coach removes for your students, across 27 lessons and 195 challenges with progress tracking built in for every student. Sixty teaching days free, no payment details required.

Start your school's free trial →