File handling is how a program reads data from, or saves data to, a file stored on secondary storage. Without file handling, all data is lost when a program closes — file handling gives programs memory that outlasts the current run.
Why is file handling important?
Think of a program's RAM as a whiteboard: fast to read and write, but wiped clean every time the whiteboard is put away (program ends). A file on a hard drive or SSD is like a notebook: slower to access, but the information stays permanently until deliberately erased. Programs that need to save high scores, user preferences, student records, or any persistent data must use file handling to write to and later read from that notebook.
What are the core file operations?
Every file handling system — regardless of language — provides four fundamental operations:
| Operation | Purpose | Typical keyword/method |
|---|---|---|
| Open | Create a connection between the program and a named file on disk | open(), OPENFILE |
| Read | Transfer data from the file into the program | read(), readline(), READFILE |
| Write | Transfer data from the program into the file | write(), WRITEFILE |
| Close | Sever the connection and ensure all data is saved | close(), CLOSEFILE |
Forgetting to close a file is a common bug: data that was written may not be flushed to disk, and the file may be locked against access by other programs.
What file modes are available?
When opening a file you must specify the mode — what you intend to do with it:
| Mode | Symbol | Behaviour |
|---|---|---|
| Read | "r" |
Open for reading only; error if file does not exist |
| Write | "w" |
Open for writing; creates file if absent, overwrites if present |
| Append | "a" |
Open for writing; creates if absent, adds to the END if present |
| Read+Write | "r+" |
Open existing file for both reading and writing |
Choosing the wrong mode is a frequent source of data loss: using "w" when you meant "a" silently deletes the existing contents.
How do you read from a file? (Step-by-step)
Pseudocode (AQA style):
OPENFILE "scores.txt" FOR READ
WHILE NOT EOF("scores.txt")
line = READFILE("scores.txt")
OUTPUT line
ENDWHILE
CLOSEFILE "scores.txt"
Python equivalent:
with open("scores.txt", "r") as f:
for line in f:
print(line.strip())
The with statement in Python automatically closes the file when the block ends — even if an error occurs. This is considered best practice and avoids forgetting close().
Worked trace — file contains three lines ("Alice:85", "Bob:72", "Carol:91"):
| Iteration | line value |
Output |
|---|---|---|
| 1 | "Alice:85" | Alice:85 |
| 2 | "Bob:72" | Bob:72 |
| 3 | "Carol:91" | Carol:91 |
| EOF reached | loop ends |
How do you write to a file?
Pseudocode:
OPENFILE "log.txt" FOR WRITE
WRITEFILE "log.txt", "Session started: 09/07/2026"
WRITEFILE "log.txt", "User logged in"
CLOSEFILE "log.txt"
Python equivalent:
with open("log.txt", "w") as f:
f.write("Session started: 09/07/2026\n")
f.write("User logged in\n")
Note the \n — Python's write() does not automatically add a newline, so you must include it manually if you want each entry on its own line. writelines() and print(..., file=f) are alternatives.
How do you append to an existing file without overwriting it?
Python:
with open("log.txt", "a") as f:
f.write("User logged out\n")
Using append mode, each new entry is added after all existing content. The log file grows with each program run rather than being replaced. This is how crash logs, audit trails, and score leaderboards are typically maintained.
How do you handle errors when a file does not exist?
Trying to open a non-existent file in read mode raises a FileNotFoundError. Programs should handle this gracefully:
Python:
try:
with open("scores.txt", "r") as f:
data = f.read()
except FileNotFoundError:
print("Score file not found. Starting fresh.")
data = ""
At GCSE, you should recognise that robust programs anticipate errors — especially file errors — rather than crashing and losing data.
Frequently asked questions
What is the difference between a text file and a binary file?
A text file stores data as human-readable characters encoded in ASCII or UTF-8 (e.g. scores.txt). A binary file stores data in its raw binary form — the direct byte representation of integers, images, or compiled programs. Text files are easier to inspect and edit; binary files are more compact and faster to read/write for structured numerical data. GCSE typically focuses on text files.
What does EOF mean?
EOF stands for End Of File — a marker or condition indicating there is no more data to read. In pseudocode, EOF("filename") returns TRUE when you have read past the last line. In Python, iterating over a file object automatically stops at EOF — the for line in f: loop simply exits when there are no more lines, without needing an explicit EOF check.
Why must files always be closed?
Closing a file flushes any buffered writes to disk (ensures data is actually saved), releases the file lock so other programs or processes can access it, and frees the file descriptor (a limited OS resource). Leaving too many files open simultaneously can exhaust the OS's file descriptor limit. Using Python's with statement makes closure automatic and eliminates the risk of forgetting.
Can a program read and write the same file at the same time?
Yes, using "r+" mode, but you must be careful about the file position pointer. After reading to the end, the pointer is at EOF — subsequent writes append. After writing, you may need to seek(0) to return to the beginning before reading. For most GCSE tasks, reading and writing are done in separate open/close cycles rather than combined, which avoids position confusion.
Work through file handling exercises with Professor Turing's step-by-step guidance at aitutors.me.