Where does your high score live?
You score 4,200 in a game. You close the app. You open it tomorrow. The score is still there.
A program forgets everything when it stops. So the score must be saved somewhere: in a file or in a database (an organised store of data).
Today you learn both.
Key words
| Word | What it means |
|---|---|
| File | A named store of data on a disk. |
| Open | Get a file ready to read or write. |
| Close | Finish with a file so its data is saved. |
| Local file | A file on the computer that runs the program. |
| Mode | What you plan to do with a file: read, write or append. |
| Database | An organised store of data that programs can search and change. |
| Table | A grid of rows and columns in a database. |
| Row | One record in a table. |
| Placeholder | A ? in SQL that marks where a value goes. |
| SQL | The language for asking a database for data. |
The cells students fill in are left blank in this preview.
The file modes
| Mode | Meaning | If the file exists | If it does not |
|---|---|---|---|
| "r" | Read | Reads it | Error |
| "w" | Write | Deletes what was there | Creates it |
| "a" | Append | Adds to the end | Creates it |
The cells students fill in are left blank in this preview.
Write, read and delete a file
import os, tempfile
folder = tempfile.mkdtemp()
path = os.path.join(folder, "scores.txt")
with open(path, "w") as handle: # with closes the file for you
handle.write("Sam 10\n")
with open(path, "a") as handle:
handle.write("Aisha 7\n")
with open(path, "r") as handle:
print(handle.read())
os.remove(path) # delete the file
print(os.path.exists(path))
Make a free account to save your work and track your progress.
Check: which mode?
Have a go
Check: which mode?
4 questionsUse "with"
Tip
The with statement closes the file for you, even if there is an error. It is the safe way. Without it, you must remember to close.
Files are not enough
A file is fine for a short list. For many users, many fields and fast search, use a database.
You change data with four jobs: add a row (INSERT), read rows (SELECT), modify a row (UPDATE) and delete a row (DELETE).
Four jobs, four SQL words
| Job | SQL | Example |
|---|---|---|
| Add | INSERT | INSERT INTO scores VALUES ('Sam', 10) |
| Read | SELECT | SELECT * FROM scores |
| Modify | UPDATE | UPDATE scores SET points = 12 WHERE name = 'Sam' |
| Delete | DELETE | DELETE FROM scores WHERE name = 'Sam' |
The cells students fill in are left blank in this preview.
Change and delete rows with SQL
UPDATE scores SET points = 12 WHERE name = 'Sam';
DELETE FROM scores WHERE name = 'Ben';
SELECT * FROM scores;
-- What happens if you forget WHERE on the DELETE?
Make a free account to save your work and track your progress.
Never forget WHERE
Warning
Many people think UPDATE or DELETE changes only the row they mean. Without WHERE, it changes every row in the table. Check the WHERE line before you run it.
Pass values safely from Python
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE scores (name TEXT, points INTEGER)")
name = "O'Neil" # a quote in the name
db.execute("INSERT INTO scores VALUES (?, ?)", (name, 5))
print(db.execute("SELECT * FROM scores").fetchall())
# The ? marks are placeholders. Never build the SQL by joining text.
Make a free account to save your work and track your progress.
Match the job
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Keep notes in a file
Write four small functions that create, read, add to and delete a file on a server. Use the with statement. The tests use a temporary folder, so your own files are safe. Press Run Tests.
def save_notes(path, lines):
# Create the file (or replace it). Write each line, then a new line character.
pass
def read_notes(path):
# Give back a list of the lines, with no new line at the end of each.
# If the file does not exist, give back an empty list.
return None
def add_note(path, line):
# Add one line to the end of the file. Keep the old lines.
pass
def remove_file(path):
# Delete the file. Give back True. If there is no such file, give back False.
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Keep scores in a database
Now keep the scores in a database. Use sqlite3 and ? placeholders. Add, change and delete a player. The tests try a name with a quote mark in it. Press Run Tests.
import sqlite3
def make_db():
# Give back a new in-memory database with a table:
# scores(name TEXT PRIMARY KEY, points INTEGER)
return None
def add_score(db, name, points):
# Insert a row. Use ? placeholders, never join the text yourself.
pass
def update_score(db, name, points):
# Change the points of an existing player.
pass
def delete_score(db, name):
# Remove the player's row.
pass
def all_scores(db):
# Give back a list of (name, points) tuples, sorted by name.
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Key words crossword
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Exit quiz
Have a go