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 | Ask the computer to get a file ready for reading or writing. |
| Close | Tell the computer you finished. It saves the data and frees the file. |
| Local file | A file on the same computer that runs the program. A file on a server works the same way in code. |
| 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 in a database. Each row is one record and each column is one fact. |
| Row | One record in a table, such as one player. |
| Placeholder | A ? in an SQL line. It marks where a value goes in safely. |
| 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.
Try it: write, read, delete
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))
Quick check: which mode?
Have a go
Quick check: which mode?
4 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
Use "with"
data-callouts.tip.label
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.
Try it: change data 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?