Files & with, explained simply
Variables are forgotten when a program ends. Files let a program remember things between runs, like a diary, a high score or a saved game.
open() takes a file name and a mode: "w" to write (replacing what was there), "a" to add to the end, and "r" to read.
Writing with open(...) as f: means Python closes the file for you when the indented block ends, even if something goes wrong. That is the safe, modern way to work with files.
Example: A journal that remembers
with open("journal.txt", "a") as f:
f.write("Saw a red kite today\n")
with open("journal.txt", "r") as f:
print(f.read())Output
Saw a red kite today\n adds a new line so each entry sits on its own line. Run it twice and the journal grows.
Try this
- Change "a" to "w", run it twice, and notice the difference.
- Save a high score to a file and read it back at the start of a game.
- Loop over a file with for line in f: to handle one line at a time.
