AQA 7517, section 4.2.1.3
Data that has to survive after a program finishes is stored in a file. Inside a file, and inside a program, related data is often grouped into records made of fields.
Fields and records
- A field is one piece of data about something, such as a name or an age. Each field has a data type.
- A record is a collection of related fields, which can have different types, treated as one item.
- A file holds a collection of records (or other data), stored permanently.
| name (string) | age (integer) | member (Boolean) |
|---|---|---|
| Asha | 17 | True |
| Ben | 18 | False |
Each row is a record, and each column is a field. Python has no built-in record type, so a dictionary can be used as the equivalent, with the field names as its keys.
s = {"name": "Asha", "age": 17, "member": True}
print(s["name"]) # Asha: one field of the record
s["age"] = 18 # fields can be changed
students = [
{"name": "Asha", "age": 17, "member": True},
{"name": "Ben", "age": 18, "member": False},
]
print(students[1]["name"]) # Ben: a list of records, like the rows of the table
A record is different from an array: an array's elements are all the same type, while a record's fields can differ.
Text files
A text file stores characters that people can read, such as .txt and .csv files. Data is read and written as strings.
Writing
with open("scores.txt", "w") as f: # "w" overwrites the file
f.write("Asha,72\n")
f.write("Ben,58\n")
with open("scores.txt", "a") as f: # "a" adds to the end
f.write("Chloe,91\n")
Reading
with open("scores.txt", "r") as f: # "r" reads the file
for line in f:
name, score = line.strip().split(",")
print(name, int(score))
Using with closes the file automatically, even if there is an error. Files should always be closed, so that all the data is saved and the file is free for other programs.
Because a text file holds only text, numbers have to be converted: you write str(score) and read back int(...).
Binary files
A binary file stores data as raw bytes, not as readable text. It is not meant to be opened in a text editor. Images, sound files and compiled programs are binary files. Programs can also use them to store records compactly.
import pickle
students = [("Asha", 17), ("Ben", 18)]
with open("students.dat", "wb") as f: # "wb" = write binary
pickle.dump(students, f)
with open("students.dat", "rb") as f: # "rb" = read binary
loaded = pickle.load(f)
print(loaded[0]) # ('Asha', 17)
| Text file | Binary file | |
|---|---|---|
| Content | Readable characters | Raw bytes |
| Open in a text editor | Yes, it makes sense | No, it looks like nonsense |
| Size | Usually larger | Usually more compact |
| Conversion needed | Numbers must be converted to and from strings | Data can be stored in its original form |
| Portable between programs | Yes, easy | Only if the format is known |
Worked example
Task: save a list of high scores to a file, then load them back and show the best.
scores = [("Asha", 72), ("Ben", 58), ("Chloe", 91)]
with open("high.txt", "w") as f:
for name, score in scores:
f.write(name + "," + str(score) + "\n")
best_name = ""
best = -1
with open("high.txt", "r") as f:
for line in f:
name, score = line.strip().split(",")
if int(score) > best:
best = int(score)
best_name = name
print(best_name, best) # Chloe 91
Each line is one record, and the comma separates the fields. When reading, strip() removes the newline, split(",") separates the fields, and int() converts the score back into a number so it can be compared.
Exam tip: state the file mode when you write file-handling code, and remember to close the file (or use with). Marks are often given for opening, reading or writing, and closing.
Check yourself
What is the difference between a field and a record?
A field is a single item of data. A record is a collection of related fields, possibly of different types, treated as one item.
What is the difference between opening a file in "w" and "a" mode?
"w" overwrites the existing contents. "a" appends, adding new data to the end and keeping what's already there.
Give one difference between a text file and a binary file
A text file holds readable characters, while a binary file holds raw bytes that aren't meant to be read directly. Numbers in a text file must be converted to and from strings.
Why should a file be closed after use?
So that all the data is written to storage and the file is released for other programs to use.