Unit 15: Files
Saving things that last.
Unit 15 of 31 in Python for kids. Its 5 lessons are Writing to a File, Reading it Back, Adding More, Checking and Deleting and File Master — below is everything each one explains, and a question or two from it to try.
Every sample on this page was run through real Python before it shipped, and prints exactly what it says it prints.
This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.
📝 Writing to a File
Making a program remember
Everything in a variable disappears when your program stops. A file stays behind. open with "w" makes one to write into.
Python
f = open("notes.txt", "w")
f.write("Hello file!\n")
f.close()
print("saved")
It prints
saved
Always close it — or let with do it
A file left open can lose what you wrote. with closes it for you the moment the block ends, even if something goes wrong. Always use with.
Python
with open("notes.txt", "w") as f:
f.write("Hello file!\n")
print("saved and closed")
It prints
saved and closed
Write does not add line breaks
Unlike print, write puts down exactly what you give it. If you want separate lines, you have to put the \n in yourself.
Python
with open("a.txt", "w") as f:
f.write("one")
f.write("two")
with open("a.txt") as f:
print(f.read())
It prints
onetwo
Where these files live
On your own computer a file stays on the disk until you delete it. Here in Alguni it lives only while your program runs — each run starts with a clean, empty folder, so always write a file in the same program that reads it.
Python
with open("scores.txt", "w") as f:
f.write("10\n")
with open("scores.txt") as f:
print(f.read().strip())
It prints
10
Try it yourself
What does the "w" mean in open("notes.txt", "w")?
- Wait
- Write — make the file, ready to be written into
- Warn
- Words only
Answer it in the app
📖 Reading it Back
The whole thing at once
Leave the mode out and open gives you the file to read. read() hands back everything in it as one piece of text.
Python
with open("t.txt", "w") as f:
f.write("cat\ndog\n")
with open("t.txt") as f:
print(f.read())
It prints
cat dog
One line at a time
Looping over an open file gives you its lines. Each one still carries its \n, so strip() tidies it off.
Python
with open("t.txt", "w") as f:
f.write("cat\ndog\n")
with open("t.txt") as f:
for line in f:
print("-", line.strip())
It prints
- cat - dog
All the lines as a list
readlines() gives you a list, so you can count them or pick one out.
Python
with open("t.txt", "w") as f:
f.write("cat\ndog\n")
with open("t.txt") as f:
lines = f.readlines()
print(len(lines))
print(lines[0].strip())
It prints
2 cat
Try it yourself
Why call strip() on each line?
- To make it lowercase
- To take off the newline character sitting at the end
- To remove the whole line
- It is not needed
What does this print?
Python
with open("n.txt", "w") as f:
f.write("3\n7\n")
total = 0
with open("n.txt") as f:
for line in f:
total = total + int(line)
print(total)
Answer them in the app
➕ Adding More
"w" wipes the file first
This is the one that catches everybody. Opening with "w" empties the file before you write a single thing — the old contents are gone.
Python
with open("d.txt", "w") as f:
f.write("first\n")
with open("d.txt", "w") as f:
f.write("second\n")
with open("d.txt") as f:
print(f.read().strip())
It prints
second
"a" adds to the end
Use "a" for append when you want to keep what is already there and add underneath.
Python
with open("d.txt", "w") as f:
f.write("first\n")
with open("d.txt", "a") as f:
f.write("second\n")
with open("d.txt") as f:
print(f.read().strip())
It prints
first second
Try it yourself
You want to add today’s score to a file of old scores. Which mode?
- "w"
- "a"
- "r"
- No mode at all
What does this print?
Python
with open("log.txt", "w") as f:
f.write("a\n")
with open("log.txt", "a") as f:
f.write("b\n")
with open("log.txt", "w") as f:
f.write("c\n")
with open("log.txt") as f:
print(f.read().strip())
Answer them in the app
🗑️ Checking and Deleting
Looking before you leap
Opening a file that is not there stops your program. os.path.exists asks first.
Python
import os
print(os.path.exists("nothing-here.txt"))
with open("real.txt", "w") as f:
f.write("hi")
print(os.path.exists("real.txt"))
It prints
False True
Or ask forgiveness instead
You can also just try it and catch the problem. FileNotFoundError is the name of that one.
Python
try:
with open("missing.txt") as f:
print(f.read())
except FileNotFoundError:
print("There is no file yet")
It prints
There is no file yet
Throwing it away
os.remove deletes a file for good. There is no undo, so it is worth checking it exists first.
Python
import os
with open("temp.txt", "w") as f:
f.write("bye")
os.remove("temp.txt")
print(os.path.exists("temp.txt"))
It prints
False
Try it yourself
What is FileNotFoundError?
- A warning you can ignore
- The name of the problem Python reports when a file is not there
- A missing folder
- A kind of file
Answer it in the app
🏆 File Master
Try it yourself
What does this print?
Python
with open("x.txt", "w") as f:
f.write("one\n")
with open("x.txt", "a") as f:
f.write("two\n")
with open("x.txt") as f:
print(len(f.readlines()))
Answer it in the app