Drop hier links of afbeeldingen om ze aan de editor toe te voegen.

In this topic students learn to read data from a text file: open it, read it line by line or one line at a time, and close it.

Learning objectives and goals

Be able to read, comprehend, trace, adapt and create Python code that:

Slide deck

This chapter was written for Dodona from new material by the course author, after the rest of the course had been converted, so it has no deck of its own. The author’s Intermediate Python series has a File handling deck that covers both reading and writing files with different examples; the Writing files chapter shares it: on Google Slides. A PDF copy is kept on Dodona too.

Teacher notes

This is the first chapter where a program’s data comes from somewhere other than the code or the keyboard. The next chapter writes files; this one only reads them, so every file is opened with "r".

The chapter shows two ways of reading a whole file, on purpose. for line in my_file: is the short form and the one students should reach for; it is a count controlled loop, one repetition per line. The while line != "": loop over .readline() is the long form, and is condition controlled. It is the same relationship as for and while in the two iteration chapters: the long form makes every step visible (read before the loop, check, read again at the end of the body), and forgetting the last step gives an infinite loop, exactly as forgetting to change a counter does. The last make task asks for the long form, so students have to write that loop out.

The reading pages cannot run code that opens a file, so file-reading examples are shown with the file’s contents and their output instead of a Run button. Every exercise’s sandbox (the To sandbox button under the editor) does have its files, and the Modify exercise’s sandbox has singers.txt, the file the predict and investigate tasks use, so that is where students can run those examples for real.

Key points

Errors and misconceptions