Learn Python · lesson 39 of 60 · about 9 minutes
Reading and Writing Files
Save the to-do list to a file and read it back, so it lasts after the assistant stops.
What you'll learn
- Write a file with open and 'w'
- Append with 'a'
- Read lines back
A to-do list that lasts
Every morning the to-do list starts empty, because variables vanish when the assistant stops. Saving it to a file fixes that. The assistant opens todo.txt with "w", writes each task followed by "\n" so it's on its own line, and then opens the file again to read it back line by line, taking the newline off each one with .strip(). Printing what came back from the file shows exactly what was saved.
Files outlive your program
Variables vanish when a program ends. Files don't. open(name, mode) opens a file; with closes it for you automatically.
| Mode | Meaning |
|---|---|
| "r" | Read (the default) |
| "w" | Write, replacing anything already there |
| "a" | Append to the end |
Write, then read
with open("notes.txt", "w") as f:
f.write("first\n")
f.write("second\n")
with open("notes.txt") as f:
print(f.read())Output
first
second
Line by line
Looping over a file gives you one line at a time, each ending in \n. .strip() removes it.
Append and count
with open("log.txt", "w") as f:
f.write("start\n")
with open("log.txt", "a") as f:
f.write("more\n")
with open("log.txt") as f:
for i, line in enumerate(f, 1):
print(i, line.strip())Output
1 start
2 moreTip
Opening a missing file for reading raises FileNotFoundError, so wrap it in try/except when the file might not exist yet.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.