23.1 Introduction: From Text File to Array of Objects
Programs rarely keep their data typed into the code. Instead the data lives in a text file, and the program loads it when it runs. In OOP that means: read each record from the file, build one object from it, and collect the objects in an array so you can search and process them.
This is one of the most common Paper 4 long-answer shapes. By the end of this page you will read records into objects, store them in an array with a counter, search the array, and wrap the file work in exception handling so a missing file does not crash the program.
- OOP combined with text-file processing and arrays.
- It assumes the class basics from Part 1 and private attributes from Part 2.
| Term | Meaning |
|---|---|
| Record | One item’s worth of data in a file — here, the lines (or one comma-separated line) that describe a single object. |
| Array of objects | A fixed-size list whose elements are objects, e.g. 30 Book objects. |
| Counter | An integer that tracks how many objects have actually been stored, separate from the array’s capacity. |
| Linear search | Checking each element of the array in turn until a match is found or the end is reached. |
| Exception | An error that happens while the program runs, such as opening a file that does not exist. |
| Exception handling | Code (try / except) that catches an exception so the program reports it instead of crashing. |
23.2 Reading a Text File into Objects
- Hard-coding data is fine for a demo, but a real catalogue lives in a file.
- The skill the exam tests is the bridge: read a record, hand its fields to a constructor, and you have an object.
- Repeat to the end of the file and you have your whole data set as objects.
- Examiner focus: “Load records from a text file into an array of objects, using exception handling” is a standard Paper 4 long-answer worth 6 to 8 marks.
- It blends section 20.1 (OOP) with section 20.2 (file processing and exception handling).
Start with a class for one record. Here each animal in a zoo has a name, species and age, stored as private attributes with a display method.
class Animal:
def __init__(self, name, species, age):
self.__name = name # private
self.__species = species # private
self.__age = age # private
def get_name(self):
return self.__name
def display_info(self):
print("Name:", self.__name, "Species:", self.__species, "Age:", self.__age)If the file stores each animal on three consecutive lines (name, species, age), read three lines, build one object, and append it to a list. strip() removes the trailing newline; int() converts the age.
zoo = [] # list to hold Animal objects
file = open("Animals.txt", "r")
for i in range(3): # three animals in the file
name = file.readline().strip()
species = file.readline().strip()
age = int(file.readline().strip())
zoo.append(Animal(name, species, age))
file.close()
for animal in zoo:
animal.display_info()
# Animals.txt:
# Leo
# Lion
# 5
# Bella
# Elephant
# 10
# ...- Read the file format carefully.
- Three-lines-per-record needs three
readline()s; one comma-separated line per record needs onereadline()thensplit(","). - Using the wrong pattern loses the reading marks.
23.2 Reading a Text File into Objects
23.3 A Fixed Object Array and a Counter
- Exam questions often require a fixed-size array (e.g. up to 30 objects) rather than a growable list, because the syllabus array has a set length.
- You then need a separate counter so you know how many slots are actually used, and an initialise step that empties the array first.
Declare the array with a capacity, initialise every slot to None, and keep an integer total of how many objects are stored. Store each new object at index total, then add 1 — but stop if the array is full.
MAX = 30
book_list = [None] * MAX # global array of up to 30 Book objects
total = 0
def initialise_array():
global total
for i in range(MAX):
book_list[i] = None
total = 0- The counter total is both the next index and the count.
- Check if total < MAX; if so store at book_list[total] and add 1; else print “List full”.
- Loop the first total slots and count matches.
- A fixed array has a capacity (its length) and a count (how many slots are filled).
- Keep them separate: store at index
count, then increasecount; never write past the capacity.
None and resetting the counter to 0 — not just declaring the array.23.3 A Fixed Object Array and a Counter
23.4 Linear Search and Exception Handling
- After loading objects you usually must find one — a linear search returns the index of a match, or -1 if there is none.
- And because a file might be missing or corrupt, the syllabus requires exception handling around file work so the program reports the problem instead of crashing.
A linear search loops through the stored objects, comparing a getter's value to the target. Wrap the file open/read in try / except so a FileNotFoundError is caught.
def find_book(title_to_find):
for i in range(total):
if book_list[i].get_title() == title_to_find:
return i # found: return the index
return -1 # not found
def load_books():
try:
file = open("Books.txt", "r")
line = file.readline()
while line != "":
title, status = line.strip().split(",")
store_book(Book(title, status))
line = file.readline()
file.close()
except:
print("File could not be opened.")- Step 1 — loop the stored slots: range(total).
- Step 2 — compare and return: return the index on a match.
- Step 3 — not found: return -1 after the loop.
- Identical shape; use get_name().
- A linear search returns the index of the first match, or -1 when nothing matches.
- Always wrap file open and read operations in
try/exceptso a missing or unreadable file is handled, not fatal.
- Returning -1 for “not found” matters because 0 is a valid index.
- Code that returns 0 on failure will look like it found the first element — examiners check for a non-index sentinel such as -1.
23.4 Linear Search and Exception Handling
23.5 Full Exam-Style Question
- A library stores its catalogue in
Books.txt. - Each line holds a title and a status separated by a comma, for example
Dune,Available.
(a) Write program code to declare a class Book with private attributes Title and Status, a constructor, GetTitle(), GetStatus() and SetStatus(newStatus). [4]
(b) Declare a global array BookList for up to 30 Book objects and a procedure InitialiseArray() that sets every element to null and the counter to 0. [4]
(c) Write a procedure LoadBooks() that opens Books.txt, reads each line to the end of file, splits it into title and status, stores a new Book in the next slot (or outputs "List full"), and uses exception handling. [6]
- (a) class Book with __init__(self, title, status) storing two private attributes; GetTitle, GetStatus, SetStatus.
- (b) BookList = [None] * 30; total = 0; InitialiseArray loops setting every element to None and resets total.
- (c) try: open file; while line != "": split(","); if total < MAX store Book and add 1, else print “List full”; readline; close; except: print error.
23.5 Full Exam-Style Question
✓ Key Points Summary
23.6 Practice Tasks
Fifteen exam-style tasks. Click Hint for bullet-point guidance, then Help to reveal a worked Python solution.
Question Bank
Answer all questions, then press Submit Quiz to see your score.
Question 1Multiple Choice
A record in a text file is:
Question 2Multiple Choice
The load pattern (file to objects) is:
Question 3True / False
Three-lines-per-record needs three readline() calls; one comma-separated line per record needs one readline() then split(",").
Question 4Multiple Choice
Why use a fixed-size array with a counter in the exam?
Question 5Multiple Choice
How do you store a new object in a fixed array with a counter?
Question 6Multiple Choice
A linear search of an object array returns:
Question 7Multiple Choice
How many slots does a linear search loop through?
Question 8True / False
Exception handling (try/except) around file work prevents the program crashing on a missing file.
Question 9Multiple Choice
What does .strip() do when reading a line from a file?
Question 10Multiple Choice
What is "initialise the array" in the exam?
Question 11Multiple Choice
In the Book exam question, LoadBooks() is worth how many marks?
Question 12Multiple Choice
Why return -1 (not 0) for "not found" in a linear search?
Answer all 12 questions to enable submission.