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

Free lesson

2.5 (3 of 3): Saving and loading with text files

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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.

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

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

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 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

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?

Make a free account to save your work and track your progress.

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.

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

Code: python
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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.

Code: python
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 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

Remember

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.

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.