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.
Make a free account to save your work and track your progress.
Open, use, then close
flowchart TD
s([Start]) --> o[Open the file, with a mode]
o --> u[Read or write lines]
u --> c[Close the file]
c --> e([End])
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
Warning
Many people think "w" adds to a file. It deletes everything that was in it first. Use "w" only when you want the file to start empty. Use "r" when you only want to look.
Choose the mode
Have a go
Choose the mode
3 questionsExtra: 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?
Make a free account to save your work and track your progress.
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.
Clean every line
Every line you read ends with a newline mark. Take it off with strip(). If a line holds several values, use split() to break them up.
The line "Sam,16" with a newline becomes ["Sam", "16"] after strip and split on the comma.
Try it: read, strip, split
file = open("people.txt", "w")
file.write("Sam,16\n")
file.write("Aisha,17\n")
file.close()
file = open("people.txt", "r")
for line in file.readlines():
parts = line.strip().split(",")
print(parts[0], "is", int(parts[1]))
file.close()
# strip() takes off the newline. split(",") breaks at the comma.
Make a free account to save your work and track your progress.
Match the code to its job
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Watch: what is in the file
Press Play on the short film below. It shows what each file holds as code like the code above opens, writes and closes it. Every newline is drawn as a mark of its own, and you will see why a line read back needs strip().
Film: saving and loading with text files
Saving and loading with text files
Every scene, as text
- Memory is cleared when a program ends, so to keep data a program must save it in a file. open("scores.txt", "w") makes scores.txt empty, ready to write. file.write("10\n") writes 10 and a newline, \n, the mark that ends a line, drawn ↵ in the file. close() saves what you wrote: scores.txt holds 10 and 20, each on its own line.
- open("scores.txt", "r") opens the file to read, keeping what is in it. file.read() gives all the text as one string, "10\n20\n", and print() shows it, then adds a newline of its own, so the screen ends with a blank line.
- Myth (false): "w" adds to a file. log.txt holds Monday. Opening it again with "w" erases everything first, so once Tuesday is written and the file closed, it holds only Tuesday: Monday is lost.
- The cure is "a", append: it keeps the old lines and adds to the end, so log.txt holds Monday, then Tuesday. Use "w" only when you want the file to start empty.
- file.readline() gives the next line each time, and the line keeps its newline: "Sam,16\n", then "Aisha,17\n". print() adds a newline of its own, so a blank line follows each.
- line = line.strip() takes the newline off, so print(line) shows Sam,16 with no blank line after it. line.split(",") breaks it at the comma into ["Sam", "16"], and int() makes "16" the number 16, so the last line shows Sam is 16.
Extra: A safer way: with
Tip
You can also write with open("a.txt") as file: and put the work underneath, indented. Python closes the file for you, even if there is an error. In the exam, closing by hand is what is asked.
Your turn: save and load
Write four functions that use text files. save_scores opens a file for writing, writes each score on its own line, and closes it. load_scores reads the lines and gives back a list of whole numbers. count_lines says how many lines a file has. parse_line turns Sam,16 into the list Sam and 16, where 16 is a whole number. Press Run Tests.
def save_scores(filename, scores):
# Open the file for writing. Write each score on its own line. Close the file.
pass
def load_scores(filename):
# Open the file for reading. Give back the scores as a list of integers.
# Each line holds one whole number.
return None
def count_lines(filename):
# Give back how many lines the file has.
return None
def parse_line(line):
# A line looks like "Sam,16" followed by a newline.
# Give back a list: the name as text, and the age as an integer.
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Key words crossword
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Exit quiz
Have a go
Exit quiz
7 questionsRemember
Important
Open the file with a mode. Read or write lines. Close it. "w" erases and writes, "r" reads. Strip each line, and split it if it holds several values.