B2.5.1 Reading and writing files
Command term: Construct1. File operation stepper
Choose a program and step through it. Watch the disk (what is really saved), the file pointer (the blue marker: where the next read starts), the buffer (text written but not yet saved) and the output.
Disk
File objects in memory
2. Mode matrix: what happens to the file?
Choose a mode, whether books.txt already exists, and what the program tries to do. Predict, then run.
Before
After
3. The loan log: overwrite or append?
Each time a book is borrowed, ShelfWise saves a line to loans.txt. Try saving several loans in mode "w", then in mode "a". Then untick close(), save a loan and simulate a crash.
Disk
4. Python and Java side by side
The syllabus lets you use either language. The ideas are the same: open, read or write, close.
Python
Java
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Predict the output
Before each snippet runs, books.txt contains three lines: Dune, Emma, Holes. Streaks of 3+ score double.
7. 45-second speed round: which mode?
Choose the file mode each task needs. A wrong answer costs 3 seconds.
The file format
One book per line, fields separated by commas: title,author,copies. Download the sample file to test load_catalogue on its own.
| Line | title | author | copies |
|---|
Expected output
Think about it
- Why does
save_catalogueuse mode "w" butlog_loanuses mode "a"? What would go wrong if they were swapped? - What happens to your file format if a title contains a comma, such as
Rich Dad, Poor Dad? How could you change the format to cope? - Why must
load_catalogueconvert the copies field withint()? What wouldcopies + 1do without it? - Run the test code twice. Why is the loan count still 2 the second time? Which test line makes that happen?
Check my code
Book class that can save and load itself.Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Save and load a reading list
Write save(filename, titles) that writes one title per line, and load(filename) that reads them back into a list without newline characters. Use with open(...) so files are always closed.
Starter file (write your code where it says pass # your code here):
def save(filename, titles):
pass # your code here
def load(filename):
pass # your code here
# ---- tests ----
save("reading.txt", ["Dune", "Emma", "三体"])
print(load("reading.txt"))
with open("reading.txt", "a", encoding="utf-8") as f:
f.write("Holes\n")
print(load("reading.txt"))
Expected output when your code is correct:
['Dune', 'Emma', '三体'] ['Dune', 'Emma', '三体', 'Holes']
Hint
Model solution
def save(filename, titles):
with open(filename, "w", encoding="utf-8") as f:
for t in titles:
f.write(t + "\n")
def load(filename):
with open(filename, "r", encoding="utf-8") as f:
return [line.rstrip("\n") for line in f]
# ---- tests ----
save("reading.txt", ["Dune", "Emma", "三体"])
print(load("reading.txt"))
with open("reading.txt", "a", encoding="utf-8") as f:
f.write("Holes\n")
print(load("reading.txt"))
Task 2: Averages from a CSV file
The program first writes marks.csv (name, subject, mark). Write averages(filename) that uses the csv module to read it, skips the header row, and returns a dictionary of each student's average mark rounded to 1 decimal place. Then write the results to averages.csv.
Starter file (write your code where it says pass # your code here):
import csv
with open("marks.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerows([["name", "subject", "mark"], ["Ana", "CS", 78], ["Ben", "CS", 64],
["Ana", "Maths", 91], ["Ben", "Maths", 70], ["Ana", "Physics", 85]])
def averages(filename):
pass # your code here
def write_averages(filename, result):
pass # your code here
# ---- tests ----
result = averages("marks.csv")
print(result)
write_averages("averages.csv", result)
print(open("averages.csv", encoding="utf-8").read())
Expected output when your code is correct:
{'Ana': 84.7, 'Ben': 67.0}
name,average
Ana,84.7
Ben,67.0
Hint
Model solution
import csv
with open("marks.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerows([["name", "subject", "mark"], ["Ana", "CS", 78], ["Ben", "CS", 64],
["Ana", "Maths", 91], ["Ben", "Maths", 70], ["Ana", "Physics", 85]])
def averages(filename):
totals = {}
with open(filename, newline="", encoding="utf-8") as f:
reader = csv.reader(f)
next(reader)
for name, subject, mark in reader:
totals.setdefault(name, []).append(int(mark))
return {name: round(sum(m) / len(m), 1) for name, m in totals.items()}
def write_averages(filename, result):
with open(filename, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["name", "average"])
for name, avg in sorted(result.items()):
w.writerow([name, avg])
# ---- tests ----
result = averages("marks.csv")
print(result)
write_averages("averages.csv", result)
print(open("averages.csv", encoding="utf-8").read())
Task 3: Analyse a library log
The program writes loans.log, with lines like 2026-11-02,S0042,borrow,Dune. Some lines are corrupted. Write analyse(filename) that returns a dictionary with: borrows, returns, bad_lines (line numbers that do not have 4 fields or a valid action), the most_borrowed title, and on_loan (titles borrowed more times than returned, sorted). If the file does not exist, print a message and return None.
Starter file (write your code where it says pass # your code here):
lines = """2026-11-02,S0042,borrow,Dune
2026-11-02,S0007,borrow,Emma
2026-11-03,S0042,return,Dune
oops this line is broken
2026-11-03,S0011,borrow,Dune
2026-11-04,S0007,renew,Emma
2026-11-04,S0019,borrow,Holes
2026-11-05,S0019,return,Holes
2026-11-05,S0042,borrow,Dune"""
with open("loans.log", "w", encoding="utf-8") as f:
f.write(lines + "\n")
def analyse(filename):
pass # your code here
# ---- tests ----
print(analyse("loans.log"))
print(analyse("missing.log"))
Expected output when your code is correct:
{'borrows': 5, 'returns': 2, 'bad_lines': [4, 6], 'most_borrowed': 'Dune', 'on_loan': ['Dune', 'Emma']}
no such file: missing.log
None
Hint
Model solution
lines = """2026-11-02,S0042,borrow,Dune
2026-11-02,S0007,borrow,Emma
2026-11-03,S0042,return,Dune
oops this line is broken
2026-11-03,S0011,borrow,Dune
2026-11-04,S0007,renew,Emma
2026-11-04,S0019,borrow,Holes
2026-11-05,S0019,return,Holes
2026-11-05,S0042,borrow,Dune"""
with open("loans.log", "w", encoding="utf-8") as f:
f.write(lines + "\n")
def analyse(filename):
try:
f = open(filename, encoding="utf-8")
except FileNotFoundError:
print("no such file:", filename)
return None
borrowed, returned, bad = {}, {}, []
with f:
for number, line in enumerate(f, start=1):
parts = line.strip().split(",")
if len(parts) != 4 or parts[2] not in ("borrow", "return"):
bad.append(number)
continue
title = parts[3]
target = borrowed if parts[2] == "borrow" else returned
target[title] = target.get(title, 0) + 1
return {
"borrows": sum(borrowed.values()),
"returns": sum(returned.values()),
"bad_lines": bad,
"most_borrowed": max(borrowed, key=borrowed.get),
"on_loan": sorted(t for t in borrowed if borrowed[t] > returned.get(t, 0)),
}
# ---- tests ----
print(analyse("loans.log"))
print(analyse("missing.log"))
Learning objectives
By the end of this page you should be able to:
- Construct programs that read from, write to and append to text files using
open(),read(),readline(),write()andclose(). - Select the appropriate file mode ("r", "w" or "a") for a task and explain what happens to existing data in each mode.
- Trace file-processing code, keeping track of the file pointer, the buffer and the contents of the file.
- Construct code that processes records stored one per line: removing the newline, splitting the fields and converting their types.
- Identify and handle common file errors: FileNotFoundError, the wrong mode, missing newlines and forgetting to close a file.
Why files?
Variables live in RAM and disappear when the program ends. A text file stores data on secondary storage so it persists. A sequential file is read from the start to the end, one line after another.
The three modes
| Mode | Use it to | If the file exists | If it does not exist | Can you read? |
|---|---|---|---|---|
"r" read (default) | load data | pointer starts at the beginning | FileNotFoundError | yes |
"w" write | save a fresh copy | contents are erased as soon as it is opened | file is created | no |
"a" append | add to the end | existing data is kept; writes go at the end | file is created | no |
The functions
f = open("books.txt", "r") # returns a file object
data = f.read() # the rest of the file as ONE string
line = f.readline() # the next line, including "\n"; "" at the end of the file
f.close() # release the file
f = open("loans.txt", "a")
f.write("Dune,Ana\n") # write() needs a str and does NOT add a newline
f.close() # buffered text is saved to disk
Reading every line
f = open("loans.txt", "r")
line = f.readline()
while line != "": # "" means end of file
parts = line.strip().split(",") # remove "\n", then split the fields
print(parts[0], int(parts[2])) # convert numbers yourself: files hold text
line = f.readline()
f.close()
The shorter loop for line in f: does the same thing. with open("books.txt") as f: closes the file automatically at the end of the block.
Why close()?
write() usually puts text in a buffer in memory; it is written to disk when the buffer is flushed, which close() does. If the program crashes before that, the data can be lost. Closing also releases the file so other programs can use it.
Common mistakes
- Using "w" when you meant "a": every save wipes the file.
- Forgetting
"\n": lines run together (DuneEmma). - Forgetting
strip()when reading: comparisons such asline == "Dune"fail because the line is"Dune\n". - Writing a number:
f.write(3)is a TypeError; usef.write(str(3)). - Opening a missing file for reading: handle FileNotFoundError with try/except (B2.1.3).
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Construct Python code that stores the titles in the list titles in the file books.txt, one title per line, replacing anything already in the file. [3]
f = open("books.txt", "w")
for t in titles:
f.write(t + "\n")
f.close()2. Distinguish between opening an existing file in write mode and in append mode. [2]
3. Each line of loans.txt has the form title,member,days, e.g. Dune,Ana,21. Construct a function count_overdue(filename) that returns how many loans have lasted more than 14 days. [5]
def count_overdue(filename):
f = open(filename, "r")
count = 0
line = f.readline()
while line != "":
parts = line.strip().split(",")
if int(parts[2]) > 14:
count = count + 1
line = f.readline()
f.close()
return count4. Explain why a program should close a file after writing to it. [2]
5. books.txt contains the lines Dune, Emma and Holes. State the output of this code. [2]
f = open("books.txt", "r")
a = f.readline()
b = f.read()
f.close()
print(len(a), b.count("\n"))
5 2. a is "Dune\n", 5 characters including the newline [1]; read() returns the rest of the file, "Emma\nHoles\n", which contains 2 newlines [1].6. A program uses open("members.txt", "w") to add a new member each time someone joins. Identify the problem and construct a corrected line of code. [3]
f = open("members.txt", "a") so new members are added to the end [1].