Lesson 16 of 35Python
Python · Lesson 16 · 25 minutes
Reading and writing files
What you'll learn
- Write and read files with
open()and with - Process the lines of a file
- Append data to a file
Data that stays
Variables forget everything as soon as the program ends. If you want to keep something – high scores, settings, measurements from your robot – you write it into a file.
Good to know: On Codelix the files live in a small, invisible storage inside the browser. They only last while the page is open. On your computer the code works exactly the same – there the files really end up on the disk.
Writing
open(name, "w") opens a file for writing. With with it’s closed automatically at the end:
with open("shopping.txt", "w") as file:
file.write("Milk\n")
file.write("Bread\n")
print("Saved!")\n is a line break. Without it everything would be in one long line.
Reading
Without a second value open() opens for reading. With a for loop you get the file line by line:
with open("shopping.txt", "w") as file:
file.write("Milk\nBread\nApples\n")
with open("shopping.txt") as file:
for number, line in enumerate(file, start=1):
print(number, line.strip())strip() removes the line break at the end of each line.
Appending
"w" deletes the old content. If you want to add something, use "a" (for append):
with open("log.txt", "w") as file:
file.write("Start\n")
for round_number in range(3):
with open("log.txt", "a") as file:
file.write(f"Round {round_number}\n")
print(open("log.txt").read())| Mode | Meaning |
|---|---|
"r" | read (default) |
"w" | write – old content is deleted |
"a" | append to the end |
Remember: Files always contain text. When reading, you have to turn numbers back with
int()orfloat().
Quick check
Before you start the task: what does this program print? Type your guess – then Python works it out.
with open("note.txt", "w") as f:
f.write("A\nB\nC\n")
with open("note.txt") as f:
print(len(f.readlines()))Your task
Your turn
Write the high scores from the list scores into the file highscores.txt – each number on its own line. Then read the file back in, add the numbers up and print Total: 52. The test also tries a different list.
scores = [12, 7, 33]
# 1. Write
# 2. Read and add up- Something to think about
Write with
file.write(f"{s}\n")– the \n makes the line break. - Which command helps?
Calculate with the numbers you read from the file – not with a total you typed in.
- Gap code – fill in the ___
scores = [12, 7, 33] with ___ as file: for s in ___: file.write(___) total = ___ with ___ as file: for line in ___: total += ___ print(___)
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
scores = [12, 7, 33]
with open("highscores.txt", "w") as file:
for s in scores:
file.write(f"{s}\n")
total = 0
with open("highscores.txt") as file:
for line in file:
total += int(line)
print(f"Total: {total}")