Chapter 5 · Real programs

Files

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 21 · Concept

A file stays when the program ends

By the end of this lesson your programs keep their data in files, as text, CSV and JSON.

Your names and objects live in memory. A file lives in storage, so it stays. Writing copies text from memory to a file; reading copies it back.

with open("notes.txt", "w") as f:
    f.write("Buy milk\n")
    f.write("Call Zoë\n")

with open("notes.txt") as f:
    text = f.read()
print(text, end="")
with open("scores.txt") as f:
    for line in f:
        print(line)
with open("scores.txt") as f:
    for line in f:
        print(line.strip())
count = 0
total = 0
# read scores.txt line by line: add 1 to count
# and the line's number to total
print("Count:", count)
print("Total:", total)
with open("notes.txt", "w") as f:
    f.write("one\n")
with open("notes.txt", "w") as f:
    f.write("two\n")
with open("notes.txt", "a") as f:
    print("three", file=f)
with open("notes.txt") as f:
    print(f.read(), end="")
try:
    with open("missing.txt") as f:
        print(f.read())
except FileNotFoundError as e:
    print("Caught:", e)
with open("log.txt", "w") as f:
    print("start", file=f)
# 1. append load, save and stop
# 2. print each line of log.txt, numbered from 1
# 3. read old.txt; when it is missing,
#    print no old log
import csv

with open("grades.csv", newline="") as f:
    rows = list(csv.DictReader(f))
print(rows[0])
total = 0
for row in rows:
    total += int(row["score"])
print("Total:", total)

with open("ada.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["subject", "score"])
    for row in rows:
        if row["name"] == "Ada":
            writer.writerow([row["subject"], row["score"]])
with open("ada.csv") as f:
    print(f.read(), end="")
import json

data = {"b": 1, "a": [1, 2.5, None, True]}
print(json.dumps(data))
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)
with open("data.json") as f:
    back = json.load(f)
print(back)
print(json.dumps({"ok": True}, indent=2))
import csv

import json
from dataclasses import dataclass, asdict


@dataclass
class Item:
    name: str
    price: int


sword = Item("sword", 30)
# 1. save sword into save.json, with indent=2
# 2. print the text of save.json
# 3. load it back into an Item named loaded
print(loaded)
print(loaded == sword)
Terminal
Step 1 of 10Write, then read

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)