Skip to content
Book 4: Practical Programming

Book 4 · Chapter P4.9

File processing and exception handling

§20.2In codeBanker · ≈ 9.2 m · ↘B4·9

This chapter is in the ebook.

Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.

Open in the ebook

§20.2 File processing and exception handling

Short code B4·9·1

Files that last

Short code B4·9·10

File = open("Scores.txt", "w")
File.write("Ali,12\n")
File.write("Bina,9\n")
File.close()
File = open("Scores.txt", "w")
File.write("Chen,15\n")
File.close()
File = open("Scores.txt", "a")
File.write("Dev,11\n")
File.close()
Count = 0
File = open("Scores.txt", "r")
for Line in File:
    print(Line.strip())
    Count = Count + 1
File.close()
print("Records:", Count)
Write mode empties the file before it writes; only append keeps the records already there.

Output

Chen,15
Dev,11
Records: 2
Run and checked before printing

Part A: records, fields and three organisations

Short code B4·9·11

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Adding a record to a serial file

Short code B4·9·12

def AppendSale(Code, Quantity):
    File = open("Sales.txt", "a")
    File.write(Code + "," + str(Quantity) + "\n")
    File.close()

File = open("Sales.txt", "w")        # start the test with an empty log
File.close()
AppendSale("B210", 3)
AppendSale("M310", 1)
AppendSale("B210", 2)

Total = 0
File = open("Sales.txt", "r")
for Line in File:
    Fields = Line.strip().split(",")
    if Fields[0] == "B210":
        Total = Total + int(Fields[1])
File.close()
print("Basil sold:", Total)
AppendSale opens the serial log in append mode, so each sale is added at the end; reading back, each record is split at the comma and the quantity converted.

Output

Basil sold: 5
Run and checked before printing
def AppendSale(Code, Quantity):
    File = open("Sales.txt", "a")
    File.write(Code + "," + str(Quantity) + "\n")
    File.close()

File = open("Sales.txt", "w")        # start the test with an empty log
File.close()
AppendSale("B210", 3)
AppendSale("M310", 1)
AppendSale("B210", 2)

Total = 0
File = open("Sales.txt", "r")
for Line in File:
    Fields = Line.strip().split(",")
    if Fields[0] == "B210":
        Total = Total + int(Fields[1])
File.close()
print("Basil sold:", Total)
The append Mark Ladder's model answer (AppendSale), with a test.

Output

Basil sold: 5
Run and checked before printing
Imports System.IO

Module Program
    Sub LogTemperature(Room As String, Temp As Integer)
        Dim Writer As New StreamWriter("Temps.txt", True)
        Writer.WriteLine(Room & "," & Temp)
        Writer.Close()
    End Sub

    Sub Main()
        Dim Empty As New StreamWriter("Temps.txt", False)
        Empty.Close()
        LogTemperature("Lab 1", 22)
        LogTemperature("Hall", 19)
        Dim Reader As New StreamReader("Temps.txt")
        Console.WriteLine(Reader.ReadToEnd().Trim())
        Reader.Close()
    End Sub
End Module
The faded twin's model answer (LogTemperature), with a test.

Output

Lab 1,22
Hall,19
Run and checked before printing

Reading records back into an array

Short code B4·9·13

class Plant:
    def __init__(self):
        self.Code = ""         # STRING, the key field
        self.Name = ""         # STRING
        self.Quantity = 0      # INTEGER

def MakeTestFile():
    File = open("Stock.txt", "w")
    for Line in ["A105,Aloe,12", "B210,Basil,40", "M310,Mint,25", "R400,Rose,8", "T520,Thyme,30"]:
        File.write(Line + "\n")
    File.close()

def LoadStock():
    Plants = []
    File = open("Stock.txt", "r")
    for Line in File:
        Fields = Line.strip().split(",")
        P = Plant()              # the record type from Chapter P4.2
        P.Code = Fields[0]
        P.Name = Fields[1]
        P.Quantity = int(Fields[2])
        Plants.append(P)
    File.close()
    return Plants

MakeTestFile()
Stock = LoadStock()
print(len(Stock), "records loaded")
for P in Stock:
    if P.Quantity < 15:
        print("Reorder", P.Code, P.Name, P.Quantity)
Each line of the file becomes one record in an array: strip, split, fill the fields, convert the number.

Output

5 records loaded
Reorder A105 Aloe 12
Reorder R400 Rose 8
Run and checked before printing

Short code B4·9·14

def MakeTestFile():
    File = open("Stock.txt", "w")
    for Line in ["A105,Aloe,12", "B210,Basil,40", "M310,Mint,25", "R400,Rose,8", "T520,Thyme,30"]:
        File.write(Line + "\n")
    File.close()

def FindPlant(Target):
    Result = "not found"
    Read = 0
    File = open("Stock.txt", "r")
    Line = File.readline().strip()
    while Line != "" and Line.split(",")[0] < Target:
        Read = Read + 1
        Line = File.readline().strip()
    if Line != "":
        Read = Read + 1
        if Line.split(",")[0] == Target:
            Result = Line
    File.close()
    return Result + " (" + str(Read) + " read)"

MakeTestFile()
print(FindPlant("M310"))
print(FindPlant("K100"))
print(FindPlant("Z900"))
A search of a sequential file stops at the first key past the target: K100 is known to be missing after 3 records, Z900 only after all 5.

Output

M310,Mint,25 (3 read)
not found (3 read)
not found (5 read)
Run and checked before printing

Output

A105 True 1
B210 True 2
M310 False 2
not found 3
Run and checked before printing

Inserting a record: copy through a temporary file

Short code B4·9·15

import os

def MakeTestFile():
    File = open("Stock.txt", "w")
    for Line in ["A105,Aloe,12", "B210,Basil,40", "M310,Mint,25", "R400,Rose,8", "T520,Thyme,30"]:
        File.write(Line + "\n")
    File.close()

def InsertPlant(NewRecord):
    NewCode = NewRecord.split(",")[0]
    Placed = False
    OldFile = open("Stock.txt", "r")
    TempFile = open("Temp.txt", "w")
    for Line in OldFile:
        Line = Line.strip()
        if not Placed and NewCode < Line.split(",")[0]:
            TempFile.write(NewRecord + "\n")
            Placed = True
        TempFile.write(Line + "\n")
    if not Placed:
        TempFile.write(NewRecord + "\n")
    OldFile.close()
    TempFile.close()
    os.remove("Stock.txt")
    os.rename("Temp.txt", "Stock.txt")

MakeTestFile()
InsertPlant("L150,Lavender,18")
InsertPlant("W610,Wallflower,6")
File = open("Stock.txt", "r")
for Line in File:
    print(Line.strip())
File.close()
Inserting into a sequential file: every record is copied to Temp.txt with the new one in its place, then Temp.txt replaces Stock.txt. W610 goes in after the loop.

Output

A105,Aloe,12
B210,Basil,40
L150,Lavender,18
M310,Mint,25
R400,Rose,8
T520,Thyme,30
W610,Wallflower,6
Run and checked before printing

Output

A105 False False A105
B210 False False B210
M310 True True L150 M310
R400 False True R400
T520 False True T520
Run and checked before printing
import os

def AddBooking(Booking):
    Placed = False
    OldFile = open("Bookings.txt", "r")
    TempFile = open("Temp.txt", "w")
    for Line in OldFile:
        if not Placed and Booking[0:4] < Line[0:4]:
            TempFile.write(Booking + "\n")
            Placed = True
        TempFile.write(Line)
    if not Placed:
        TempFile.write(Booking + "\n")
    OldFile.close()
    TempFile.close()
    os.remove("Bookings.txt")
    os.rename("Temp.txt", "Bookings.txt")

File = open("Bookings.txt", "w")
File.write("0900,Ali\n0945,Sana\n1100,Omar\n")
File.close()
AddBooking("1030,Huma")
AddBooking("1600,Zain")
File = open("Bookings.txt", "r")
print(File.read().strip())
File.close()
The insertion Mark Ladder's model answer (AddBooking): 1030 goes in its place and 1600 goes in after the loop.

Output

0900,Ali
0945,Sana
1030,Huma
1100,Omar
1600,Zain
Run and checked before printing
import java.io.*;

public class Main {
    static void DeleteBooking(String Time) throws IOException {
        BufferedReader OldFile = new BufferedReader(new FileReader("Bookings.txt"));
        FileWriter TempFile = new FileWriter("Temp.txt");
        String Line = OldFile.readLine();
        while (Line != null) {
            if (!Line.substring(0, 4).equals(Time)) {
                TempFile.write(Line + "\n");
            }
            Line = OldFile.readLine();
        }
        OldFile.close();
        TempFile.close();
        new File("Bookings.txt").delete();
        new File("Temp.txt").renameTo(new File("Bookings.txt"));
    }

    public static void main(String[] args) throws IOException {
        FileWriter Writer = new FileWriter("Bookings.txt");
        Writer.write("0900,Ali\n0945,Sana\n1100,Omar\n");
        Writer.close();
        DeleteBooking("0945");
        BufferedReader Reader = new BufferedReader(new FileReader("Bookings.txt"));
        String Line = Reader.readLine();
        while (Line != null) {
            System.out.println(Line);
            Line = Reader.readLine();
        }
        Reader.close();
    }
}
The faded twin's model answer (DeleteBooking): every booking except 0945 is copied.

Output

0900,Ali
1100,Omar
Run and checked before printing

Deleting and changing a record

Short code B4·9·16

import os

def MakeTestFile():
    File = open("Stock.txt", "w")
    for Line in ["A105,Aloe,12", "B210,Basil,40", "M310,Mint,25", "R400,Rose,8", "T520,Thyme,30"]:
        File.write(Line + "\n")
    File.close()

def CopyChanging(Code, NewQuantity):
    # NewQuantity -1 deletes the record; any other value replaces its quantity
    OldFile = open("Stock.txt", "r")
    TempFile = open("Temp.txt", "w")
    for Line in OldFile:
        Fields = Line.strip().split(",")
        if Fields[0] != Code:
            TempFile.write(Line)
        elif NewQuantity != -1:
            TempFile.write(Fields[0] + "," + Fields[1] + "," + str(NewQuantity) + "\n")
    OldFile.close()
    TempFile.close()
    os.remove("Stock.txt")
    os.rename("Temp.txt", "Stock.txt")

MakeTestFile()
CopyChanging("R400", -1)
CopyChanging("B210", 35)
File = open("Stock.txt", "r")
for Line in File:
    print(Line.strip())
File.close()
The same copy deletes a record (Rose) or changes one (Basil's quantity becomes 35).

Output

A105,Aloe,12
B210,Basil,35
M310,Mint,25
T520,Thyme,30
Run and checked before printing

Random files: fixed-length records

Short code B4·9·17

import struct

LAYOUT = "<12si"        # 12 bytes of text, then a whole number in 4 bytes
print(struct.calcsize(LAYOUT))
Packed = struct.pack(LAYOUT, "Hamza".encode(), 1207)
Holder, Code = struct.unpack(LAYOUT, Packed)
print(Holder.decode().rstrip("\x00"), Code)
Python's struct packs a 12-byte name and a 4-byte whole number into a 16-byte record, and unpacks them again.

Output

16
Hamza 1207
Run and checked before printing

Seek, read, change, write back

Short code B4·9·18

RECORD_LENGTH = 16     # Holder 12 + Form 3 + line end 1

def MakeRecord(Holder, Form):
    return Holder[0:12].ljust(12) + Form[0:3].ljust(3) + "\n"

def PutRecord(Number, Record):
    File = open("Lockers.dat", "r+b")
    File.seek((Number - 1) * RECORD_LENGTH)
    File.write(Record.encode())
    File.close()

def GetRecord(Number):
    File = open("Lockers.dat", "rb")
    File.seek((Number - 1) * RECORD_LENGTH)
    Record = File.read(RECORD_LENGTH).decode()
    File.close()
    return Record

File = open("Lockers.dat", "wb")        # six empty lockers
for Count in range(6):
    File.write(MakeRecord("", "").encode())
File.close()

PutRecord(3, MakeRecord("Hamza", "12C"))
PutRecord(5, MakeRecord("Sana", "13A"))
Record = GetRecord(5)                   # read, change, write back
PutRecord(5, MakeRecord(Record[0:12].strip(), "13B"))
for Number in range(1, 7):
    Record = GetRecord(Number)
    if Record[0:12].strip() == "":
        print(Number, "free")
    else:
        print(Number, Record[0:12].strip(), Record[12:15])
A random file of 16-byte records: seek to (n − 1) × 16, then read or write exactly one record. Sana's form is changed by read, change, write back.

Output

1 free
2 free
3 Hamza 12C
4 free
5 Sana 13B
6 free
Run and checked before printing
RECORD_LENGTH = 16

def ChangeForm(Number, NewForm):
    File = open("Lockers.dat", "r+b")
    File.seek((Number - 1) * RECORD_LENGTH)
    Record = File.read(RECORD_LENGTH).decode()
    Record = Record[0:12] + NewForm.ljust(3) + "\n"
    File.seek((Number - 1) * RECORD_LENGTH)
    File.write(Record.encode())
    File.close()

File = open("Lockers.dat", "wb")
File.write(("Hamza".ljust(12) + "12C\n" + "Sana".ljust(12) + "13A\n").encode())
File.close()
ChangeForm(2, "13B")
File = open("Lockers.dat", "rb")
print(File.read().decode().strip())
File.close()
The random-file Mark Ladder's model answer (ChangeForm): Sana's form becomes 13B, her name is kept.

Output

Hamza       12C
Sana        13B
Run and checked before printing
Imports System.IO
Imports System.Text

Module Program
    Const RecordLength As Integer = 16

    Sub ClearLocker(Number As Integer)
        Dim Lockers As New FileStream("Lockers.dat", FileMode.Open)
        Lockers.Seek((Number - 1) * RecordLength, SeekOrigin.Begin)
        Lockers.Write(Encoding.ASCII.GetBytes(Space(15) & vbLf), 0, RecordLength)
        Lockers.Close()
    End Sub

    Sub Main()
        Dim Writer As New StreamWriter("Lockers.dat", False)
        Writer.Write("Hamza".PadRight(12) & "12C" & vbLf & "Sana".PadRight(12) & "13A" & vbLf)
        Writer.Close()
        ClearLocker(1)
        Dim Reader As New StreamReader("Lockers.dat")
        Console.WriteLine("[" & Reader.ReadLine() & "]")
        Console.WriteLine("[" & Reader.ReadLine() & "]")
        Reader.Close()
    End Sub
End Module
The faded twin's model answer (ClearLocker): locker 1 becomes 15 spaces and a line end.

Output

[               ]
[Sana        13A]
Run and checked before printing

Choosing a file organisation

Short code B4·9·19

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Part B: what an exception is

Short code B4·9·20

import os
if os.path.exists("Prices.txt"):     # make sure the file is missing for this test
    os.remove("Prices.txt")
Total = 0
File = open("Prices.txt", "r")
for Line in File:
    Total = Total + int(Line)
File.close()
print("Total:", Total)
Unhandled: the file is missing, so open raises FileNotFoundError and the program halts (Python report, last lines).
Run and checked before printing
File = open("Prices.txt", "w")      # make a test file with a bad line
File.write("40\n12a\n25\n")
File.close()

Total = 0
File = open("Prices.txt", "r")
for Line in File:
    Total = Total + int(Line)
File.close()
print("Total:", Total)
Unhandled: the line 12a cannot be converted, so int raises ValueError and the program halts with no total (Python report, last lines).
Run and checked before printing

Output

FileNotFoundError: [Errno 2] No such file or directory: 'Prices.txt'
ValueError: invalid literal for int() with base 10: '12a\n'
Run and checked before printing

Output

System.IO.FileNotFoundException: Could not find file '…/Prices.txt'.
System.FormatException: The input string '12a' was not in a correct format.
System.InvalidCastException: Conversion from string "12a" to type 'Integer' is not valid.
Run and checked before printing

Output

java.io.FileNotFoundException: Prices.txt (No such file or directory)
java.lang.NumberFormatException: For input string: "12a"
Run and checked before printing

Catching an exception: the Paper 4 pattern

Short code B4·9·21

def LoadReadings(FileName):
    Readings = []
    try:
        File = open(FileName, "r")
        for Line in File:
            Readings.append(int(Line))
        File.close()
    except FileNotFoundError:
        print("Cannot open " + FileName)
    return Readings

File = open("Week2.txt", "w")       # test data: Week1.txt does not exist
File.write("18\n21\n19\n")
File.close()
for Name in ["Week1.txt", "Week2.txt"]:
    Readings = LoadReadings(Name)
    print(Name, "gave", len(Readings), "readings")
print("Program finished")
The Paper 4 pattern: open, read and close inside the try; a missing file is reported by name and the program carries on.

Output

Cannot open Week1.txt
Week1.txt gave 0 readings
Week2.txt gave 3 readings
Program finished
Run and checked before printing
def CountLines(FileName):
    Count = 0
    try:
        File = open(FileName, "r")
        for Line in File:
            Count = Count + 1
        File.close()
    except FileNotFoundError:
        print("Cannot find " + FileName)
    return Count

File = open("Jobs.txt", "w")
File.write("one\ntwo\nthree\n")
File.close()
print(CountLines("Jobs.txt"))
print(CountLines("Diary.txt"))
The exception Mark Ladder's model answer (CountLines), with a file that exists and one that does not.

Output

3
Cannot find Diary.txt
0
Run and checked before printing
import java.io.*;

public class Main {
    static String ReadFirst(String FileName) {
        String First = "";
        try {
            BufferedReader Reader = new BufferedReader(new FileReader(FileName));
            First = Reader.readLine();
            Reader.close();
        } catch (IOException Problem) {
            System.out.println("Cannot open " + FileName);
        }
        return First;
    }

    public static void main(String[] args) throws IOException {
        FileWriter Writer = new FileWriter("Menu.txt");
        Writer.write("Soup\nRice\n");
        Writer.close();
        System.out.println(ReadFirst("Menu.txt"));
        System.out.println("[" + ReadFirst("Specials.txt") + "]");
    }
}
The faded twin's model answer (ReadFirst), with a file that exists and one that does not.

Output

Soup
Cannot open Specials.txt
[]
Run and checked before printing

Catching the exception you expect

Short code B4·9·22

def LoadReadings(FileName):
    Readings = []
    try:
        File = open(FileName, "r")
        for Line in File:
            Readings.append(int(Line))
        File.close()
    except FileNotFoundError:
        print("Cannot open " + FileName)
    except ValueError:
        print("A line in " + FileName + " is not a whole number")
    return Readings

File = open("Week3.txt", "w")       # test data: the second line has a letter l, not a 1
File.write("18\n2l\n19\n")
File.close()
for Name in ["Week1.txt", "Week3.txt"]:
    Readings = LoadReadings(Name)
    print(Name, "gave", len(Readings), "readings")
Two handlers, checked in order. The bad line skips the rest of the try block, so Week 3 gives one reading and its file is never closed.

Output

Cannot open Week1.txt
Week1.txt gave 0 readings
A line in Week3.txt is not a whole number
Week3.txt gave 1 readings
Run and checked before printing

finally, and files that close themselves

Short code B4·9·23

def AddUp(FileName):
    Total = 0
    File = None
    try:
        File = open(FileName, "r")
        for Line in File:
            Total = Total + int(Line)
        print("try finished")
    except FileNotFoundError:
        print("no file")
    except ValueError:
        print("bad line")
    finally:
        print("finally runs")
        if File is not None:
            File.close()
    return Total

File = open("Good.txt", "w")        # test data: Gone.txt does not exist
File.write("5\n7\n")
File.close()
File = open("Bad.txt", "w")
File.write("5\nx\n7\n")
File.close()
for Name in ["Good.txt", "Bad.txt", "Gone.txt"]:
    print(Name, AddUp(Name))
The finally block runs in all three cases: no exception, a handled ValueError, and a missing file.

Output

try finished
finally runs
Good.txt 12
bad line
finally runs
Bad.txt 5
no file
finally runs
Gone.txt 0
Run and checked before printing

Validating input with exceptions

Short code B4·9·24

def GetQuantity():
    Valid = False
    while not Valid:
        try:
            Quantity = int(input("Quantity (1 to 50): "))
            if Quantity >= 1 and Quantity <= 50:
                Valid = True
            else:
                print("Out of range")
        except ValueError:
            print("Whole numbers only")
    return Quantity

print("Accepted:", GetQuantity())
Validation: the conversion in a try block catches ten; an IF refuses 70; 12 is accepted. Inputs: ten, 70, 12.

Output

Quantity (1 to 50): Whole numbers only
Quantity (1 to 50): Out of range
Quantity (1 to 50): Accepted: 12
Run and checked before printing

Raising your own exceptions

Short code B4·9·25

def Sell(Stock, Number):
    if Number < 1:
        raise ValueError("Number sold must be at least 1")
    if Number > Stock:
        raise ValueError("Only " + str(Stock) + " in stock")
    return Stock - Number

Stock = 12
for Number in [5, 0, 9, 7]:
    try:
        Stock = Sell(Stock, Number)
        print("Sold", Number, "- left", Stock)
    except ValueError as Problem:
        print("Refused:", Problem)
Sell checks with IF and raises an exception with a message; the caller catches it, reports it and carries on.

Output

Sold 5 - left 7
Refused: Number sold must be at least 1
Refused: Only 7 in stock
Sold 7 - left 0
Run and checked before printing
class BadRecord(Exception):
    pass

def CheckRecord(Line):
    Fields = Line.split(",")
    if len(Fields) != 3:
        raise BadRecord("expected 3 fields, found " + str(len(Fields)))
    return Fields

for Line in ["A105,Aloe,12", "B210,Basil"]:
    try:
        print(CheckRecord(Line)[1], "is fine")
    except BadRecord as Problem:
        print(Line, "-", Problem)
An exception type of your own, a subclass of the language's exception class, raised for a record with the wrong number of fields.

Output

Aloe is fine
B210,Basil - expected 3 fields, found 2
Run and checked before printing

When an exception is the plan: binary files of records

Short code B4·9·26

import pickle

class Visit:
    def __init__(self):
        self.Name = ""        # STRING
        self.Minutes = 0      # INTEGER

File = open("Visits.dat", "wb")
for Name, Minutes in [("Omar", 45), ("Lina", 30), ("Yusuf", 60)]:
    V = Visit()
    V.Name = Name
    V.Minutes = Minutes
    pickle.dump(V, File)
File.close()

Total = 0
EndOfFile = False
File = open("Visits.dat", "rb")
while not EndOfFile:
    try:
        V = pickle.load(File)
        print(V.Name, V.Minutes)
        Total = Total + V.Minutes
    except EOFError:
        EndOfFile = True
File.close()
print("Total minutes:", Total)
A binary file of records is read until reading past the end raises an exception: EOFError, EndOfStreamException, EOFException.

Output

Omar 45
Lina 30
Yusuf 60
Total minutes: 135
Run and checked before printing

Putting it together on Paper 4

Short code B4·9·27

def LoadReadings(FileName):
    Readings = []
    Skipped = 0
    try:
        File = open(FileName, "r")
        for Line in File:
            try:
                Readings.append(int(Line))
            except ValueError:
                Skipped = Skipped + 1
        File.close()
        print(FileName + ":", len(Readings), "read,", Skipped, "skipped")
    except FileNotFoundError:
        print(FileName + ": file not found")
    return Readings

File = open("Week3.txt", "w")       # test data: one bad line; Week1.txt does not exist
File.write("18\n2l\n19\n23\n")
File.close()
AllReadings = LoadReadings("Week1.txt") + LoadReadings("Week3.txt")
Highest = AllReadings[0]
for Reading in AllReadings:
    if Reading > Highest:
        Highest = Reading
print("Highest:", Highest)
Two levels of handling: the outer try reports a missing file; the inner one skips and counts a bad line. Neither stops the program.

Output

Week1.txt: file not found
Week3.txt: 3 read, 1 skipped
Highest: 23
Run and checked before printing

Past-paper practice

Short code B4·9·90

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Workbook 4: File processing and exception handling

Short code W4·9 · Practical Programming Task Book

The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.

Starter files

Short code W4·9·K

Data files and skeleton code in Python, VB.NET, Java for this chapter's tasks arrive here with the chapter.

Ask Z about File processing and exception handling
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook