🧰 Standard Library Tour, lesson 5 of 7
Reading and writing files
Save data that outlives your program with open(), write() and read().
10 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Every value your programs have stored so far vanished
when they stopped running. Files fix that:
open(filename, mode) hands you a file object.
| Mode | Meaning |
|---|---|
"r" |
read (the default) — the file must exist |
"w" |
write — creates the file, or erases it if it exists |
"a" |
append — adds to the end, keeping what's there |
Wrap the work in with open(...) as f: — you met
with in the Errors module as automatic cleanup.
It closes the file for you, even if an error happens
halfway through.
Write a file, then read it back
write adds nothing on its own: without the \\ns
the file would be one long line. Run it twice — mode
"w" starts the file from scratch each time.
What does this print?
Lines, one at a time
Every line keeps its trailing \\n — that's why
strip() shows up so often. Looping over the file
reads one line at a time, which matters for big files.
What does this print?
Append mode: a little diary
Run it again: the diary keeps growing, because
"a" never throws anything away.
Shopping list on disk
Write two functions:
save_cart(items)writes each item tocart.txt, one per line.load_cart()readscart.txtback and returns the list of items, without the\\ncharacters.
The check saves one cart, inspects the file, then loads a different cart it wrote itself — so both functions have to use the file.