CHAPTER 7 · 5 lessons · 65 exercises
Reading and writing files
Leave data outside your program, so your values are still there once it has finished running.
From here on it gets more advanced. This is the first of six chapters that take you from "I can write Python" to "I can read other people's Python".
Every program you have written shares one property: when it finishes, every value it was holding disappears. Variables, lists, dictionaries — they exist only while the program runs, and next time round everything is blank again.
The first way past that is a file. Write some text outside the program and it survives; read it back the next time you run. A notes app, a budget tracker, a game's save data — underneath, all of them are this.
You open a file with open. Once opened it has to be closed, and forgetting can leave what you wrote only half saved. That is what with is for. Write with open("memo.txt") as f: and Python closes it for you when the indented block ends. It makes forgetting structurally impossible, which is why real code almost always looks like this.
For reading we cover two shapes: a line at a time, and the whole thing at once. To work line by line you write for line in f: — and here you notice that Chapter 2's for works on a file too, unchanged. That feeling of "the same way of writing keeps working everywhere" gets explained properly in Chapter 8.
For writing you give a mode, as in open("memo.txt", "w"). One warning: "w" wipes what is already there before it writes. To add to the end you want "a". Accidentally emptying a file that mattered is a mistake experienced people still make.
Note that file work in this course happens in a made-up file area inside your browser. It never touches the real files on your device, so try "w" freely. The catch is that the area is rebuilt on every run, so you cannot have the experience of "the file I wrote last time is still here". Within a single run, we go as far as writing a file and reading it back.
Lessons in this chapter
Reading
- 75Open a file and read itOpen with
open, read withread, close withclose. This is about things that outlive the run.Go to the exercises - 76Have it closed for youWrite
withand Python closes the file for you as the indented block ends.Go to the exercises - 77Reading a line at a time
for line in f:loops over a file. Theforfrom Chapter 2 works on files unchanged.Go to the exercises
Writing
- 78Writing out to a file
"w"wipes the contents before it writes. Use it unawares and a file that mattered ends up empty.Go to the exercises - 79Write it, then read it backSave it, and fetch it out again. A notes app, a budget tracker, a game save — the root of all of them is this round trip.Go to the exercises