Home › Theme B › B2 › B2.5 › B2.5.1

B2.5.1 Reading and writing files

Command term: Construct

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

Program:

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.

Mode books.txt exists? Action

Before

After

Predict first: what will the program return or raise, and what will books.txt contain afterwards?

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.

Mode Title Member

Disk

loans.txt already has one loan in it.

4. Python and Java side by side

The syllabus lets you use either language. The ideas are the same: open, read or write, close.

Task:

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: which mode?

Choose the file mode each task needs. A wrong answer costs 3 seconds.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 5, task 1. Until now, everything ShelfWise knew vanished when the program stopped. Make it persistent: save the catalogue to a text file, load it back at start-up (even if the file does not exist yet), and keep a loan log that grows every time a book is borrowed.

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.

Linetitleauthorcopies

Expected output

[['Dune', 'Herbert', 3], ['Emma', 'Austen', 1], ['Holes', 'Sachar', 2]] [] 2 Dune,Ana Emma,Ben 3

Think about it

  • Why does save_catalogue use mode "w" but log_loan uses 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_catalogue convert the copies field with int()? What would copies + 1 do 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

    Next sprint (B3.1): ShelfWise's books become objects, with a 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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    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):

    File: b2_5_1_average.py
    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
    Mode "w" overwrites, "a" appends, "r" reads.
    Model solution
    File: b2_5_1_average_solution.py
    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"))
    
    Moderate

    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):

    File: b2_5_1_moderate.py
    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
    Every value read from a CSV file is a string; convert marks with int().
    Model solution
    File: b2_5_1_moderate_solution.py
    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())
    
    Challenging

    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):

    File: b2_5_1_challenging.py
    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
    Count borrows and returns per title in two dictionaries.
    Model solution
    File: b2_5_1_challenging_solution.py
    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:

    1. Construct programs that read from, write to and append to text files using open(), read(), readline(), write() and close().
    2. Select the appropriate file mode ("r", "w" or "a") for a task and explain what happens to existing data in each mode.
    3. Trace file-processing code, keeping track of the file pointer, the buffer and the contents of the file.
    4. Construct code that processes records stored one per line: removing the newline, splitting the fields and converting their types.
    5. 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

    ModeUse it toIf the file existsIf it does not existCan you read?
    "r" read (default)load datapointer starts at the beginningFileNotFoundErroryes
    "w" writesave a fresh copycontents are erased as soon as it is openedfile is createdno
    "a" appendadd to the endexisting data is kept; writes go at the endfile is createdno

    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 as line == "Dune" fail because the line is "Dune\n".
    • Writing a number: f.write(3) is a TypeError; use f.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]

    Open books.txt in write mode "w" [1]; loop through the list, writing each title followed by "\n" [1]; close the file [1].
    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]

    Write mode erases the existing contents when the file is opened, so the file holds only the new data [1]; append mode keeps the existing contents and adds new data at the end of the file [1].

    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]

    Open the file for reading [1]; loop until the end of the file / through every line [1]; strip and split each line on "," [1]; convert the days field with int() and add 1 to a counter if it is greater than 14 [1]; close the file and return the counter [1].
    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 count

    4. Explain why a program should close a file after writing to it. [2]

    Written data may still be held in a buffer in memory; closing flushes it to the file on disk, so it is not lost if the program stops [1]; closing releases the file / system resources so other programs or later parts of the program can open it [1].

    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]

    Mode "w" erases the file every time it is opened [1], so only the most recent member is kept [1]. Correction: f = open("members.txt", "a") so new members are added to the end [1].