×

python · level 2 · unit 6 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.