Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

OS 6.1 (3 of 10): Files and data on a server

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

60 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it means
FileA named store of data on a disk.
OpenGet a file ready to read or write.
CloseFinish with a file so its data is saved.
Local fileA file on the computer that runs the program.
ModeWhat you plan to do with a file: read, write or append.
DatabaseAn organised store of data that programs can search and change.
TableA grid of rows and columns in a database.
RowOne record in a table.
PlaceholderA ? in SQL that marks where a value goes.
SQLThe language for asking a database for data.

The cells students fill in are left blank in this preview.

The file modes

ModeMeaningIf the file existsIf it does not
"r"ReadReads itError
"w"WriteDeletes what was thereCreates it
"a"AppendAdds to the endCreates it

The cells students fill in are left blank in this preview.

Write, read and delete a file

Code: python
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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Use "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

JobSQLExample
AddINSERTINSERT INTO scores VALUES ('Sam', 10)
ReadSELECTSELECT * FROM scores
ModifyUPDATEUPDATE scores SET points = 12 WHERE name = 'Sam'
DeleteDELETEDELETE FROM scores WHERE name = 'Sam'

The cells students fill in are left blank in this preview.

Change and delete rows with SQL

Code: 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

Code: 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.

Code: python
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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.