Reading and writing files

Standard Library Tour, lesson 5 of 7

🧰 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.

Example

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.

Quiz

What does this print?

Example

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.

Quiz

What does this print?

Example

Append mode: a little diary

Run it again: the diary keeps growing, because "a" never throws anything away.

Exercise

Shopping list on disk

Write two functions:

  1. save_cart(items) writes each item to cart.txt, one per line.
  2. load_cart() reads cart.txt back and returns the list of items, without the \\n characters.

The check saves one cart, inspects the file, then loads a different cart it wrote itself — so both functions have to use the file.