Files and databases · GCSE · about 25 min
Log every run to a file, load the file into a table, and find the best run with SQL.
[1 mark]In the logbook, why is the file used as well as the database table?
[1 mark]logbook.csv has a header line and four runs. How many lines does the file have?
[1 mark]Which query finds the fastest run?
[1 mark]What happens to the logbook if the program opens logbook.csv with mode "w" to add a run?
Build the program from the brief. Print runs logged: <n> using SELECT COUNT(*), and fastest: run <n> at <speed> cm/s with the speed rounded to 1 decimal place, using ORDER BY. The task types 28, and starts from the four-run logbook above every time.
# the two lines every program starts with: the commands, then the robot from bugbot import * connect() import sqlite3
The hint students can ask for: Read the file to find the next run number; drive and time; append; CREATE TABLE and INSERT every line; SELECT COUNT(*); SELECT run, cm / seconds ... ORDER BY cm / seconds DESC.
from bugbot import *
connect()
import sqlite3
far = float(input("How far? "))
with open("logbook.csv") as f:
lines = f.read().splitlines()
next_run = len(lines)
start = clock()
forward(50, distance=far)
seconds = round(clock() - start, 1)
with open("logbook.csv", "a") as f:
f.write(f"{next_run},{far:g},{seconds}\n")
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE runs (run INTEGER PRIMARY KEY, cm REAL, seconds REAL)")
with open("logbook.csv") as f:
f.readline()
for row in f:
run, cm, secs = row.strip().split(",")
db.execute("INSERT INTO runs VALUES (?, ?, ?)", (int(run), float(cm), float(secs)))
count = db.execute("SELECT COUNT(*) FROM runs").fetchone()[0]
print("runs logged:", count)
run, speed = db.execute("SELECT run, cm / seconds FROM runs ORDER BY cm / seconds DESC").fetchone()
print(f"fastest: run {run} at {round(speed, 1)} cm/s")
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.