Edexcel International Advanced Level Computer Science, point 17.2.3
You must be able to select and use appropriate libraries, files, modules and subprograms to build a solution. The concepts are in 9.1.3 (modularity in code), 8.2.3 (text files) and 7.1.4 (subprograms). Check the PLS for the libraries you may use.
Libraries
A library (module) is ready-made code you load with import.
| Library | Used for | Example |
|---|---|---|
math |
Maths functions | math.sqrt(16), math.pi, math.ceil(2.1) |
random |
Random numbers and choices | random.randint(1, 6), random.choice(items) |
datetime |
Dates and times | datetime.date.today() |
time |
Delays and timing | time.sleep(1) |
re |
Regular expressions (18.1.2) | re.findall(...) |
json |
Reading and writing JSON | json.load(f) |
csv |
Reading and writing CSV files | csv.reader(f) |
sqlite3 |
SQLite databases (8.3) | sqlite3.connect(...) |
collections |
deque, Counter |
Counter(words) |
decimal |
Exact decimal arithmetic (18.1.1) | Decimal("0.1") |
numpy, pandas |
Arrays and data analysis (18.1.3, 18.1.4) | installed separately |
import math
import random
from collections import Counter
from datetime import date
print(math.sqrt(49), math.pi)
print(random.choice(["a", "b", "c"]) in "abc")
print(Counter("mississippi").most_common(2)) # [('i', 4), ('s', 4)]
print(date(2026, 11, 15).strftime("%d/%m/%Y")) # 15/11/2026
Choosing: import x keeps names in the module's own namespace (x.func()), and avoids clashes. from x import f is shorter, but can overwrite names.
Dates and times in the PLS
The Program Language Subset stores a moment in time as a timestamp: the number of seconds since the epoch (1 January 1970, 00:00:00 UTC). Time zones are ignored; pass timezone.utc so every result is in UTC.
| Subprogram | Gives |
|---|---|
datetime.fromtimestamp(stamp, timezone.utc) |
A datetime object for a timestamp |
datetime.now(timezone.utc) |
The current date and time |
datetime.strptime(text, "%Y-%m-%d %H:%M:%S") |
A datetime object read from a string |
obj.strftime("%H:%M:%S") |
A formatted string (here, just the time) |
obj.date() |
Just the date part |
obj.timestamp() |
The timestamp (a real number) |
from datetime import datetime, timezone
stamp = 1767225600 # seconds since the epoch
when = datetime.fromtimestamp(stamp, timezone.utc)
print(when.strftime("%Y-%m-%d %H:%M:%S")) # 2026-01-01 00:00:00
print(when.date()) # 2026-01-01
print(when.timestamp()) # 1767225600.0
d = datetime.strptime("2026-03-15 09:30:00", "%Y-%m-%d %H:%M:%S")
print(f"{d:%d/%m/%Y}") # 15/03/2026
Exam tip: practical questions often store times as timestamps in a list or file; convert each one with fromtimestamp when you print it, and leave the original data unchanged.
Files
Text files (8.2.3)
with open("notes.txt", "w") as f:
f.write("first line\nsecond line\n")
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
CSV files (comma-separated values)
import csv
with open("marks.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "mark"])
writer.writerow(["Amy", 72])
writer.writerow(["Raj", 91])
with open("marks.csv", "r", newline="") as f:
reader = csv.DictReader(f) # each row as a dictionary
rows = [(r["name"], int(r["mark"])) for r in reader]
# [('Amy', 72), ('Raj', 91)]
print(rows)
Remember: everything read from a file is text, so convert numbers.
JSON files (structured data)
JSON stores dictionaries, lists, strings, numbers, Booleans and null, and is common for configuration and web data (6.3.4).
import json
data = {"name": "Amy", "marks": [60, 70, 80], "member": True}
with open("student.json", "w") as f:
json.dump(data, f, indent=2)
with open("student.json", "r") as f:
loaded = json.load(f)
print(loaded["marks"]) # [60, 70, 80]
Choosing a file format
| Format | Best for |
|---|---|
| Plain text | Simple lists, logs, notes |
| CSV | Tables of data (spreadsheets, 18.1.4) |
| JSON | Nested or structured data |
| Database (SQLite) | Large data, searching, relationships (8.3) |
Handling file errors
try:
with open("data.csv") as f:
content = f.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Not allowed to read that file")
Modules (your own files)
Put related subprograms in their own .py file, then import it.
File shapes.py:
PI = 3.14159
def circle_area(r):
return PI * r ** 2
# runs only when this file is run directly
if __name__ == "__main__":
print(circle_area(2))
File main.py:
import shapes
print(shapes.circle_area(3)) # 28.27431
- The
if __name__ == "__main__":guard stops test code running when the file is imported. - Benefits: organised code, reuse, separate testing, teamwork (9.1.3).
Subprograms
Break the program into small functions and procedures with one job each (7.1.4):
def read_scores(filename): # input
with open(filename) as f:
return [int(line) for line in f if line.strip()]
def summarise(marks): # processing
return {"count": len(marks),
"mean": sum(marks) / len(marks),
"max": max(marks)}
def report(summary): # output
for key, value in summary.items():
print(f"{key}: {value}")
def main():
marks = read_scores("marks.txt")
report(summarise(marks))
Separating input, processing and output (9.1.2) lets you test summarise without a file.
Worked example
Task: a program must read student marks from a CSV file, work out each student's grade, and write the results to a JSON file. Use libraries, files, modules and subprograms.
# grades.py (module with the logic)
def grade_for(mark):
if mark >= 70:
return "A"
if mark >= 50:
return "B"
return "C"
# main.py
import csv
import json
import grades # our own module
def read_marks(filename):
with open(filename, newline="") as f:
return [(r["name"], int(r["mark"])) for r in csv.DictReader(f)]
def write_results(filename, results):
with open(filename, "w") as f:
json.dump(results, f, indent=2)
def main():
try:
marks = read_marks("marks.csv")
except FileNotFoundError:
print("marks.csv not found")
return
results = {name: grades.grade_for(m) for name, m in marks}
write_results("results.json", results)
print(results)
main()
With marks.csv holding Amy 72 and Raj 55, results.json contains {"Amy": "A", "Raj": "B"}. It used: csv and json libraries, CSV and JSON files, our own module (grades), small subprograms, and error handling.
Exam tip: know which library or format suits which job, and why (CSV for tables, JSON for nested data). Always use with for files, convert text to numbers, and handle FileNotFoundError. Keep logic in subprograms so that it is easy to test.
Check yourself
Why use the with statement when opening a file?
It closes the file automatically, even if an error occurs.
What type is data read from a CSV file, and what must you do with numbers?
Text (strings), so numbers must be converted with int() or float().
What does if __name__ == "__main__": do?
It makes the code under it run only when the file is run directly, not when it is imported as a module.
Give one reason to use JSON instead of CSV
JSON can hold nested and structured data (lists and dictionaries inside each other), whereas CSV holds flat tables.