Course outline · 0% complete

0/27 lessons0%

Course overview →

Files: reading and writing from zero

lesson 8-0 · ~11 min · 20/27

Programs that remember

Everything you have computed so far vanished the moment the program ended, because variables live only in memory. Real software must persist data: save the game, keep a log, read yesterday's records back in. The operating system's unit of durable storage is the file, a named sequence of bytes on disk, and Python's built-in open() is the door to it.

f = open("todo.txt", "w")   # open for writing
f.write("buy milk\n")
f.close()

open(path, mode) returns a file object, your handle on the open file. The mode string declares your intent:

ModeMeaning
"r"read (the default)
"w"write, erasing whatever the file held
"a"append to the end

write puts text into the file exactly as given, so you add the \n line breaks yourself. close() tells the operating system you are done, which flushes any buffered text to disk and frees the handle. Forgetting it risks losing the last writes.

Code exercise · python

Run this program. It creates the file, writes two lines, then reopens it for reading and prints each line. The strip() removes the trailing newline every line carries.

Three ways to read

  • f.read() returns the whole file as one string, fine for small files.
  • f.readlines() returns a list of the lines.
  • for line in f: streams one line at a time, the professional default.

The loop works because a file object is an iterator over its lines, the lesson 4-1 protocol again. Two consequences follow from what you already know about iterators:

  • Lines arrive one at a time, so a 10-gigabyte log file never has to fit in memory.
  • The iterator is one-shot: a second loop over the same open file gets nothing, because the read position is already at the end.

Every line keeps its trailing \n, so strip() is the usual companion, and int(line) works directly because int ignores surrounding whitespace.

Code exercise · python

Your turn. Write the three numbers to nums.txt, one per line (str(n) + "\n"), and close the file. Then reopen it for reading, add up its lines with int(line), close it, and print the total.

Quiz

notes.txt already holds 100 lines. What does open("notes.txt", "w") do to them?