Stage 9 Working with Files
Lesson 9 of 12 +10 XP

Files: Making Data Stick Around

Everything we have done so far disappears when the program stops. Variables? Gone. Calculated results? Vanished. If you want your Python program to save data permanently — like a game saving your high score — you need to write it to a file.

Sarpanch
Variables live in RAM — temporary memory that gets wiped when you close your program. Files live on your hard drive. That's why we write to files! 💾

The open() function and modes

Everything starts with the built-in open() function. It takes two things: the filename, and a mode that tells Python what you intend to do with the file.

📖
"r"
Read
Open to read. Fails if file doesn't exist.
✏️
"w"
Write
Creates file if needed. Overwrites existing content.
➕
"a"
Append
Adds to the end without deleting existing content.

Getting data out of a file

After opening a file in read mode, you can use several methods to get its contents.

  • .read() — returns the entire file as one big string.
  • .readline() — returns just one line at a time.
  • .readlines() — returns a list where each item is one line of the file.
file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()   # Always close when done!

Saving data to a file

Open the file in write mode "w" to create a file and write to it. Use "a" (append) if you want to add to a file without destroying what's already there.

save_score.py
# Write mode — creates or overwrites
file = open("score.txt", "w")
file.write("High Score: 9500\n")
file.close()

# Append mode — adds to the end
file = open("score.txt", "a")
file.write("Second Run: 8700\n")
file.close()
3file.write("...")Write does NOT add a newline automatically. You add \n yourself to move to the next line.
4file.close()You MUST close the file when done. Leaving it open wastes system resources and can corrupt data.

The safer, smarter way to open files

Remembering to call file.close() every time is annoying and easy to forget. Python provides a cleaner approach: the with statement. It automatically closes the file for you the moment you're done with it, even if an error occurs.

# The Pythonic way — no manual close() needed!
with open("notes.txt", "r") as file:
    content = file.read()
    print(content)

# File is automatically closed here ✅
💡 Pro Tip: Always use with open(...) as file:. It's cleaner, safer, and it's what professional Python developers use.

Working with files is like working with a physical notebook.

open("r"): Taking the notebook off the shelf to read it.
open("w"): Tearing out all the pages and starting fresh on a blank notebook.
open("a"): Opening to the last page and continuing to write from where you left off.
close() / with: Putting the notebook back on the shelf when you're done. If you don't, it could fall off the desk and get damaged!

Read vs Write vs Append

notes.txt on disk read() Python variable write("w") OVERWRITES! New content replaces all append("a") adds to end Old content + new line
Read pulls data from disk into Python. Write and Append push data from Python back to disk.

The Diary

Panel 1
Sarpanch
"I wrote 3 whole pages of my diary. Time to add today's entry!"

open("diary.txt", "w")
Panel 2
Sarpanch
"Perfect! I wrote today's entry. Let me read it back..."
Panel 3
Sarpanch
"It only shows today's entry. Those 3 pages are gone forever."

"w" mode overwrites. He needed "a" mode!

Reading and Writing Files

Since we're running in the browser, we'll simulate file reading and writing using Python's built-in tools.

💡 Challenges:
  1. Read the file back using open("scores.txt", "r") and print the contents.
  2. Change the write mode to "a" and see how a second run appends instead of overwriting.
  3. Loop over readlines() to print each score on its own line.

Working with Files — Done! 📄

  • Use open(filename, mode) to open a file.
  • "r" = Read, "w" = Write (overwrites!), "a" = Append (adds to end).
  • After opening, use .read(), .readline(), or .readlines() to get content.
  • Use .write("text") to write. Remember \n for new lines.
  • Always close() a file when done, or better yet use the with open(...) as file: block which closes automatically.
Sarpanch victorious
Your programs can now have a memory! They can save data, read it back, and keep track of things even after closing. Next up is one of the biggest ideas in programming: Object-Oriented Programming! 🏗️