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

Everything a program has stored so far disappears the moment it stops. The variables, the lists, the total you worked so hard to add up: run the program again and they all start from scratch.

Data that has to last longer than one run is kept in a file. A high score table, a list of passwords, a class’s exam results: all of those are saved in a file, and a program that needs them opens the file and reads them back in.

The simplest kind is a text file, which holds nothing but lines of text. This one is called singers.txt and holds eleven names, one per line:

Kurt
Debbie
Freddie
Karen
Dave
Brittany
Jon
Gladys
John
Gwen
Geddy

This program opens that file and prints every line in it:

my_file = open("singers.txt", "r")

for line in my_file:
    print(line)

my_file.close()

It has three parts: open the file, read it, close it. Every program in this chapter has the same three.

The code blocks on the reading pages of this chapter cannot open files, so they are shown without a Run button, next to the contents of the file they read and the output they give. The exercises are different: each one comes with its files, and the To sandbox button at the bottom of an exercise’s editor takes the files along, so you can try your code there before you submit it.

Opening the file

my_file = open("singers.txt", "r")

If Python cannot find a file with that name, the program stops on this line with a FileNotFoundError. That is nearly always a spelling mistake in the name, or a missing .txt.

Reading every line

for line in my_file:
    print(line)

This is a for loop, but instead of a range it works through the file, the way for letter in word works through a string in the String manipulation chapter. It repeats once for every line in the file, and each time round the variable line holds the next line, as a string. The first time it holds Kurt, the second time Debbie, and so on until the file runs out.

That makes it a count controlled loop, just like a loop over a range. The program does not have to know how many lines there are, but the file does: the loop repeats exactly that many times and then stops by itself.

line is an ordinary variable name, the same as the counter in a range loop, so you could call it something else. line says what it holds, which is why you will see it in most programs that read files.

Closing the file

my_file.close()

Once the program has finished with a file, it closes it. That tells the computer the program no longer needs it, so other programs can use it again. The line is not indented: it runs once, after the loop has finished reading.

Forgetting to close a file you have only read from rarely causes a visible problem in a small program. It does matter as soon as you start writing to files, so make it a habit now.

Every line ends with a newline

Run the program above and this is what you get:

Kurt

Debbie

Freddie

Karen

Dave

Brittany

Jon

Gladys

John

Gwen

Geddy

There is a blank line after every name, and it is not a mistake in the program. A text file is really one long piece of text, and the end of each line is marked with a hidden newline character, written \n in Python. When the loop reads a line, the newline comes along with it, so the first line is not "Kurt" but "Kurt\n".

print then adds a newline of its own, as it always does. Two newlines in a row give you the blank line.

Removing the newline with .strip()

.strip() gives you a copy of a string with the spaces and newlines at the start and the end taken off. Anything in the middle is left alone, so "The Beatles\n".strip() is "The Beatles".

my_file = open("singers.txt", "r")

for line in my_file:
    name = line.strip()
    print(name)

my_file.close()

This version prints the eleven names one below the other, without the gaps.

Like .lower() and .upper() from the String manipulation chapter, .strip() does not change the string it is used on. It hands back a new one, so store it in a variable (name here) or use it straight away.

The blank lines are harmless when all you do is print. The newline matters much more when you compare a line with something, since a string with a newline on the end is not equal to the same string without one. Keep that in mind for the tasks that follow.

Help! My code doesn't work!

Make sure that you check for the following things:

  • The file name is a string, in quotes, and ends in .txt.
  • The mode is "r", in quotes, after a comma.
  • The opened file is stored in a variable, and that same variable name is used in the for line and in the .close() line.
  • The for line has a colon (:) at the end, and the code to repeat is indented under it.
  • .close() is not indented, so it runs once after the loop.
  • Every line still has its newline on the end. Use .strip() if that gets in the way.