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
| Word | What it means | Example |
|---|---|---|
| Text file | A file that holds plain text, line by line. | scores.txt |
| Open | Get a file ready to read or write. | open("scores.txt", "r") |
| Close | Finish with a file. This saves what you wrote. | file.close() |
| Read | Take data out of a file into the program. | file.read() |
| Write | Put data from the program into a file. | file.write("Sam") |
| Line | One row of text in a file. It ends with a newline. | "Sam,16\n" |
| Newline | The hidden mark that ends a line. Python writes it as \n. | \n |
| List | One name that holds many values in order. | ["a", "b"] |
| String | Text inside quote marks. | "Sam" |
The cells students fill in are left blank in this preview.
Try it: write a file, then read it
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
| Mode | Meaning | If the file is missing | Old content |
|---|---|---|---|
| `"r"` | Read | An error (FileNotFoundError) | Kept |
| `"w"` | Write | It is made | Erased 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 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
Extra: Try it: a third mode, append
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
| Code | What it gives | For 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.