python · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Read a file all at once, or .
open("scores.txt") with no mode opens a file for reading. file.read() hands back everything in it as one string, newlines and all.
Loop over the file instead and you get it line by line: for line in file:. Each line still ends with its \n, so .strip() it before you use it, and convert numbers as usual.
Open a file that does not exist and you get a . Catch it with try whenever a file might not be there yet.
with open("scores.txt", "w") as file:
file.write("12\n30\n8\n")
total = 0
with open("scores.txt") as file:
for line in file:
total = total + int(line.strip())
print(f"Total: {total}") Each lesson writes its own file first, because every run starts in an empty folder.
guess first
Lines that keep their newlines. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
with open("pets.txt", "w") as file:
file.write("cat\ndog\n")
with open("pets.txt") as file:
for line in file:
print(line)
your turn
Your turn. Find the longest word in a file.
Write three words of your own into the file, one in each blank. Then fill in the method that trims each line before it is measured.
fix it
The notes app crashes on day one. Can you fix it?
- Read the last line of the error. Which error happened, and which one is the
exceptwaiting for? - The file is not found, but the
exceptnames a different error, FileExistsError, so it never catches it. - Change FileExistsError to FileNotFoundError on line 4, then run.
nailed it
you read files like a pro. :D
file.read()gives the whole file as one string.for line in file:goes line by line, so strip each one.- Catch FileNotFoundError when a file might not exist yet.
new words in your collection
- line by line
- FileNotFoundError
This lesson isn’t saved. A free account remembers every lesson you finish.