You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Programs often need to store data permanently — after the program closes, the data should still be available the next time it runs. File handling allows programs to read from and write to text files. This is a key topic for GCSE Computer Science (AQA 3.2 / OCR J277 2.2).
Variables only exist while a program is running. When the program ends, all variable data is lost. Files provide persistent storage — data saved to a file remains available after the program closes.
Common uses of file handling:
There are three main file operations:
| Operation | Description | Pseudocode | Python mode |
|---|---|---|---|
| Read | Opens a file and reads its contents | OPENREAD | "r" |
| Write | Creates a new file (or overwrites existing) and writes data | OPENWRITE | "w" |
| Append | Opens an existing file and adds data to the end | OPENAPPEND | "a" |
Warning:
OPENWRITE/ mode"w"will overwrite the entire file. If you want to add to an existing file, use append.
file ← OPENWRITE("scores.txt")
file.WRITELINE("Alice,85")
file.WRITELINE("Bob,72")
file.CLOSE()
file = open("scores.txt", "w")
file.write("Alice,85\n")
file.write("Bob,72\n")
file.close()
Or using a with statement (recommended in Python — automatically closes the file):
with open("scores.txt", "w") as file:
file.write("Alice,85\n")
file.write("Bob,72\n")
Note: In Python,
write()does not automatically add a newline — you must include\nyourself.
with open("scores.txt", "r") as file:
contents = file.read()
print(contents)
file ← OPENREAD("scores.txt")
WHILE NOT file.ENDOFFILE()
line ← file.READLINE()
OUTPUT line
ENDWHILE
file.CLOSE()
with open("scores.txt", "r") as file:
for line in file:
print(line.strip())
The .strip() method removes the trailing newline character from each line.
with open("scores.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
Appending adds new data to the end of an existing file without deleting its current contents.
file ← OPENAPPEND("scores.txt")
file.WRITELINE("Charlie,91")
file.CLOSE()
with open("scores.txt", "a") as file:
file.write("Charlie,91\n")
Files often store data in a structured format with fields separated by commas (CSV). You can split each line to extract individual values:
with open("scores.txt", "r") as file:
for line in file:
parts = line.strip().split(",")
name = parts[0]
score = int(parts[1])
print(f"{name} scored {score}")
target = input("Enter name to search for: ")
found = False
with open("scores.txt", "r") as file:
for line in file:
parts = line.strip().split(",")
if parts[0] == target:
print(f"Found: {parts[0]} scored {parts[1]}")
found = True
if not found:
print("Name not found")
flowchart TD
A[Start] --> B{Choose mode}
B -->|Read| C[OPENREAD filename]
B -->|Write| D[OPENWRITE filename]
B -->|Append| E[OPENAPPEND filename]
C --> F[READLINE in loop]
D --> G[WRITELINE data]
E --> G
F --> H{End of file?}
H -->|No| F
H -->|Yes| I[CLOSE file]
G --> I
I --> J[End]
| Operation | Pseudocode |
|---|---|
| Open for reading | file ← OPENREAD("filename.txt") |
| Open for writing | file ← OPENWRITE("filename.txt") |
| Open for appending | file ← OPENAPPEND("filename.txt") |
| Read a line | line ← file.READLINE() |
| Write a line | file.WRITELINE("data") |
| Check end of file | file.ENDOFFILE() |
| Close the file | file.CLOSE() |
Files may not always exist or be accessible. In Python, you can handle this with try...except:
try:
with open("scores.txt", "r") as file:
contents = file.read()
print(contents)
except FileNotFoundError:
print("Error: File not found.")
Exam Tip: In pseudocode you are unlikely to be asked about error handling with files, but in Python-based questions showing
try...exceptdemonstrates good practice.
def add_contact(name, phone):
with open("contacts.txt", "a") as file:
file.write(f"{name},{phone}\n")
print("Contact added.")
def view_contacts():
try:
with open("contacts.txt", "r") as file:
for line in file:
parts = line.strip().split(",")
print(f"Name: {parts[0]}, Phone: {parts[1]}")
except FileNotFoundError:
print("No contacts found.")
# Main menu
while True:
choice = input("1) Add 2) View 3) Quit: ")
if choice == "1":
name = input("Name: ")
phone = input("Phone: ")
add_contact(name, phone)
elif choice == "2":
view_contacts()
elif choice == "3":
break
file.CLOSE() in pseudocode or a with statement in Python."w" erases the file first.line.strip() removes trailing \n."r") retrieves data from an existing file."w") creates a new file or overwrites an existing one."a") adds data to the end of an existing file.with statement).split() to extract fields.strip() to remove trailing newline characters when reading.scores = [
("Ali", 95),
("Bea", 88),
("Cai", 77),
]
with open("highscores.txt", "w") as file:
for name, score in scores:
file.write(f"{name},{score}\n")
After running, highscores.txt contains:
Ali,95
Bea,88
Cai,77
top_name = ""
top_score = -1
with open("highscores.txt", "r") as file:
for line in file:
parts = line.strip().split(",")
if len(parts) == 2:
name = parts[0]
score = int(parts[1])
if score > top_score:
top_score = score
top_name = name
print(f"Top: {top_name} with {top_score}")
Expected output: Top: Ali with 95
def record_score(name, score):
with open("highscores.txt", "a") as file:
file.write(f"{name},{score}\n")
record_score("Dia", 91)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.