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

In this topic students learn to save data from a program into a text file, replacing the file with write mode or adding to it with append mode.

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 Reading files chapter shares it: on Google Slides. A PDF copy is kept on Dodona too.

Teacher notes

This chapter is the second half of file handling. The previous chapter covers reading a file; this one covers writing to one. The shape is the same in both (open, work with the file, close), and the new idea is the mode: "w" and "a" alongside the "r" students already know.

The chapter is built around one question students should ask before they open a file: when the program has finished, should the file still hold what it held before? If not, write mode; if so, append mode. The predict task is set up so that the answer to “did writing.txt change?” is not obvious: the program writes Bob to a file whose first line was already Bob, so a student who reads the output rather than the code thinks nothing happened, and misses that Sarah is gone.

Key points

Errors and misconceptions