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

Everything a program keeps in its variables disappears the moment the program ends. Run it again and the names, scores and answers from last time are gone. A text file does not have that problem: whatever is written into it stays there, ready for the next run of the program, or for a different program altogether.

The previous chapter took data out of a file. This one puts data in. The shape is the same three steps: open the file, do something with it, and close it again.

my_file = open("writing.txt", "w")
my_file.write("Bob")
my_file.close()

Opening a file for writing

my_file = open("writing.txt", "w")

open takes two pieces of text. The first is the name of the file, extension included. The second is the mode: what you are going to do with the file. "r" opens a file to read it, and "w" opens it to write to it.

The result is stored in a variable, here my_file. Everything the program does to the file after this goes through that variable.

Write mode does two things that read mode never does:

Opening a file in "w" mode wipes it. Use write mode when the program is meant to replace what is in the file. When it has to keep what is there and add more, you need append mode, which is the next activity.

Writing text

my_file.write("Bob")

write puts the text between the brackets into the file. It looks like print, but it behaves differently in two ways that both matter.

write does not start a new line. print moves on to the next line every time; write does not. These two lines

my_file.write("Bob")
my_file.write("Sarah")

leave the file holding BobSarah on one line. To end a line you write the newline character yourself. It is written \n, a backslash followed by the letter n, inside the quotes, and Python stores it as the single invisible character that means “the line ends here”.

my_file.write("Bob\n")
my_file.write("Sarah\n")

That gives two lines, Bob and Sarah. When the text is in a variable, join the newline on with a +, the same way you join any two pieces of text:

name = "Dave"
my_file.write(name + "\n")

write only takes text. print(7) works, but my_file.write(7) stops the program with a TypeError. A number has to go through str() first, exactly as it does when you join it onto text:

score = 7
my_file.write("Score: " + str(score) + "\n")

Closing the file

my_file.close()

Python does not always send what you write straight to the file. It may keep it in memory for a moment and save it in one go. Closing the file is what makes sure everything has been saved, and it lets other programs use the file again. Close every file you open, as soon as you have finished with it.

Try it yourself

This program writes a shopping list to a file, then opens the file again in read mode to show you what ended up in it. Run it, then delete the Milk line and run it again: Milk is gone from the file too, since write mode starts the file from empty every time.

my_file = open("shopping.txt", "w")
my_file.write("Eggs\n")
my_file.write("Milk\n")
my_file.write("Bread\n")
my_file.close()

my_file = open("shopping.txt", "r")
for line in my_file:
    print(line.strip())
my_file.close()

The reading half is the loop from the previous chapter, with .strip() taking the \n off each line so that the items are not printed with gaps between them. The \n is still in the file: it is what puts each item on a line of its own.

Help! My code doesn't work!

Make sure that you check for the following things:

  • The mode is in quotes and in lower case: "w", not w or "W".
  • The file name includes its extension: "results.txt", not "results".
  • Every line you write ends with "\n", or the next piece of text carries on from where the last one stopped.
  • Numbers go through str() before they are written.
  • write and close are called on the variable that holds the file: my_file.write(...), not write(...).
  • The file is closed, with brackets: my_file.close(), not my_file.close.