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.
Be able to read, comprehend, trace, adapt and create Python code that:
"w") or append mode ("a") and closes it"\n"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.
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.
"w" creates the file if it does not exist and empties it if it does, at
the moment it is opened."a" creates the file if it does not exist and keeps it if it does; new
text goes after the last character.write does not add a newline. Every line ends with "\n", written by hand,
or the next piece of text carries on along the same line.write only takes text, so numbers go through str() first.close makes sure what was written has been saved. Close every file as soon
as the program has finished with it.True or False. Used as a flag, it keeps a loop
going until something inside the loop sets it to False. Students met one
in the 2D arrays chapter; this chapter uses it in every program from the
investigate task on."\n". Names run together on one line. Students coming from
print expect a new line for free. The investigate question on line 6 is the
place to make this explicit.open
inside the loop with "w" wipes each student with the next, and ends up with
only the last one.close. The investigate task asks what happens without it. The
honest answer is “possibly nothing you can see”, because Python usually saves
the data anyway when the variable is reused or the program ends. That is
worth discussing: a bug that does not always show is still a bug.n ends the loop. In the starter program N, no and typing
mistakes all count as “yes, another one”. The validation challenge exists to
fix exactly that, and it is a good bridge to discussing why input should be
checked at all.