Tutorial 15/15 — Final Module
ADVANCED TECHNIQUES
Python: File Handling
Permanent data storage. Variables vanish, files stay.
The Hook
Variables are like RAM (Temporary). Turn off the power, they vanish.
Files are like the Hard Drive (Storage). Save today, load next month!
The Data Pipeline:
"w"
Write Mode (Overwrites EVERYTHING)
"a"
Append Mode (Adds to the bottom)
Worked Example
Saving a High Score to disk.
# Writing Data
# 1. Open ('w' = Write)
file = open("score.txt", "w")
# 2. Write Data
file.write("1000")
# 3. Close (Saves it!)
file.close()
# Reading Back
# 1. Open ('r' = Read)
file = open("score.txt", "r")
# 2. Read All Content
data = file.read()
# 3. Use it
print(data)
Logic Gate
Predict Output
File "notes.txt" contains "Buy Milk". Run this:
f = open("notes.txt", "w")
f.write("Buy Bread")
f.close()
f.write("Buy Bread")
f.close()
Virtual Laboratory Storage Vector
Empty Sector Monitor...
Level 40: Bronze
Guest Book
"Change the filename to 'guest.txt' and save YOUR NAME inside."
> bronze_stream_standby
Level 41: Silver
Data Wipe Disaster
"Change mode 'w' to 'a' (Append). Run it TWICE to see two logs grow."
> debugger_module_monitoring
Level 42: Gold
Chat Logger
Independent Search Pattern
- Ask for a message using
input(). - Open
"chat.txt"in Append mode. - Write the message +
"\n"to the file. - CRITICAL: Close the file to save!
> computation_vector_online