CIE AS & A Level Computer Science, section 20.2 (File processing and exception handling)
Text files
# write (creates or overwrites)
with open("names.txt", "w") as f:
f.write("Aisha\n")
f.write("Ben\n")
# append (adds to the end)
with open("names.txt", "a") as f:
f.write("Cara\n")
# read line by line
with open("names.txt", "r") as f:
for line in f:
print(line.strip())
In CIE pseudocode: OPENFILE ... FOR READ/WRITE/APPEND, READFILE, WRITEFILE, EOF and CLOSEFILE.
Records in a file
A file of records can be stored using pickle, which saves a whole record (object) in one go.
import pickle
students = [{"id": 3, "name": "Cara"}, {"id": 1, "name": "Aisha"}, {"id": 2, "name": "Ben"}]
# serial file: written in the order the records arrive
with open("students.dat", "wb") as f:
for s in students:
pickle.dump(s, f)
# read all the records
with open("students.dat", "rb") as f:
while True:
try:
print(pickle.load(f))
except EOFError:
break
Sequential file
Records sorted by a key, such as id. To keep the file in order, write the records sorted, and to add one, merge it into a new file.
with open("sorted.dat", "wb") as f:
for s in sorted(students, key=lambda r: r["id"]):
pickle.dump(s, f)
Random (direct) file
Records are all the same size so the position of record is record size. Use seek to jump straight to a record.
import struct
FORMAT = "i10s" # an int, then 10 bytes of text
SIZE = struct.calcsize(FORMAT)
with open("random.dat", "wb") as f:
for s in students:
f.write(struct.pack(FORMAT, s["id"], s["name"].encode()))
with open("random.dat", "rb") as f:
f.seek(1 * SIZE) # record number 1
rid, name = struct.unpack(FORMAT, f.read(SIZE))
print(rid, name.rstrip(b"\x00").decode()) # 1 Aisha
Good practice
Always close the file (with does this automatically), and check the file exists before reading.
Common mistake: opening a file with "w" when you meant to add to it: "w" erases the old contents. Use "a" to append. Also, forgetting to close a file can lose data that has not been written.
Exam tip: say the mode (read, write, append) and close the file. For random files, explain that the position is calculated from the record number and size, then use seek.
Check yourself
What happens if you open an existing file for writing?
Its old contents are erased and replaced.
Why must records in a random file be the same size?
So the position of any record can be calculated, as record number multiplied by record size.
How can a record be added to a sequential file and keep it in order?
Merge the new record into the correct place and write the result to a new file.