Card 15: Files

Module 6: Advanced Techniques

1 The Hook

Variables are like RAM (Short-term memory). Turn off the power, they vanish.

Files are like the Hard Drive (Long-term memory). Save now, load next week.

Modes: "w" (Write/Overwrite) vs "a" (Append/Add).

2 Worked Example

Saving a high score.

# 1. Open file (Creates it if missing)
file = open("score.txt", "w")
# 2. Write data (Must be String)
file.write("1000\n")
# 3. Close to save
file.close()

Reading Back

file = open("score.txt", "r") # "r" for Read
data = file.read()
print(data) # Prints "1000"

Reading Line-by-Line (The Loop)

file = open("names.txt", "r")
for line in file:
print(line.strip()) # strip() removes the \n

PREDICT

You run this code. What happens to "notes.txt"?

# notes.txt contains "Buy Milk"
f = open("notes.txt", "w")
f.write("Buy Bread")
f.close()

Interactive Editor

> _
[No files yet]
BRONZE (MODIFY)

🥉 Guest Book

1. Change the filename to "guest.txt".
2. Change the message to write YOUR name (e.g. "James").
3. Run and check the Virtual Disk below.

> _
SILVER (FIX)

🥈 Data Wipe Disaster

This logger keeps deleting old data because it uses "w" (Write/Overwrite) mode!
1. Change "w" to "a" (Append).
2. Run it TWICE. You should see "Log Entry" appear twice in the Virtual Disk.

> _
GOLD (MAKE)

🥇 Chat Logger

1. Ask user for a msg.
2. Open "chat.txt" in Append mode.
3. Write the message + "\n" (New Line).
4. Close file.

> _
Previous: Strings Next: Algorithms
```