python · level 2 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
opens a , and closes it when you are done.
Variables vanish when a program ends, but a file stays. with open("diary.txt", "w") as file: opens a file for writing and names it file. When the indented block ends, with closes the file for you.
file.write("...") adds text to the file. It never starts a new line by itself, so end each line with the character \n.
The "w" wipes the file and starts fresh, and the mode "a" adds to the end instead. In Gwecode, every run starts in an empty folder.
with open("diary.txt", "w") as file:
file.write("Saw a fox.\n")
file.write("Ate a pie.\n")
with open("diary.txt", "a") as file:
file.write("Went to bed.\n")
with open("diary.txt") as file:
print(file.read()) open("diary.txt") with no mode opens the file for reading, which is the next lesson's job.
guess first
Write, then write again. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
with open("list.txt", "w") as file:
file.write("eggs\n")
with open("list.txt", "w") as file:
file.write("milk\n")
with open("list.txt") as file:
print(file.read())
your turn
Your turn. Keep a to-do list.
Fill in the mode that writes a fresh file. Then add two jobs of your own: each blank sits before a newline already.
fix it
The guest book only remembers one guest. Fix it!
- The file is opened once for every guest. What does mode
"w"do each time it opens? "w"wipes the file, so each guest wipes out the one before. You need the mode that adds to the end.- Change "w" to "a" on line 2, then run.
nailed it
your programs can remember now. :D
with open(name, mode) as file:closes the file for you."w"starts fresh, and"a"adds to the end.- End every line you write with
\n.
new words in your collection
- file
- with
- mode
- newline
This lesson isn’t saved. A free account remembers every lesson you finish.