Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

Saving and loading with text files

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

45 minutes

A game that forgets your score

You beat your high score. You close the game. You open it again. The score is gone.

Variables (names that hold values) live in memory, and memory is cleared when the program ends. To keep data, a program must save it in a file.

Key words

WordWhat it meansExample
Text fileA file that holds plain text, line by line.scores.txt
OpenGet a file ready to read or write.open("scores.txt", "r")
CloseFinish with a file. This saves what you wrote.file.close()
ReadTake data out of a file into the program.file.read()
WritePut data from the program into a file.file.write("Sam")
LineOne row of text in a file. It ends with a newline."Sam,16\n"
NewlineThe hidden mark that ends a line. Python writes it as \n.\n
ListOne name that holds many values in order.["a", "b"]
StringText inside quote marks."Sam"

The cells students fill in are left blank in this preview.

Try it: write a file, then read it

Code: python
file = open("scores.txt", "w")
file.write("10\n")
file.write("20\n")
file.close()

file = open("scores.txt", "r")
print(file.read())
file.close()

# "w" is for writing. "r" is for reading.
# Add a line that writes 30.

The two modes

ModeMeaningIf the file is missingOld content
`"r"`ReadAn error (FileNotFoundError)Kept
`"w"`WriteIt is madeErased first

The cells students fill in are left blank in this preview.

Mode w erases the file

data-callouts.warning.label

Opening a file with "w" deletes everything that was in it. Many programmers lose data by choosing the wrong mode. Use "r" when you only want to look.

Choose the mode

Have a go

Choose the mode

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Extra: Try it: a third mode, append

Code: python
file = open("log.txt", "w")
file.write("Monday\n")
file.close()

file = open("log.txt", "a")
file.write("Tuesday\n")
file.close()

file = open("log.txt", "r")
print(file.read())
file.close()

# "a" means append: add to the end and keep the old lines.
# Change "a" to "w" and run it. Which day is lost?

Three ways to read

CodeWhat it givesFor a file with the lines a, b, c
`file.read()`All the text as one string"a\nb\nc\n"
`file.readline()`The next line"a\n" then "b\n" then "c\n"
`file.readlines()`A list of all the lines["a\n", "b\n", "c\n"]

The cells students fill in are left blank in this preview.

The lesson goes on

8 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.