Writing a file
Python · Unit 17: Files
- Full plan
- Python
- 10 exercises
Everything you keep in a variable is gone when the program ends. A file stays.
open(name, "w") opens a file for writing, write puts text in it and close closes and saves it.
The last line of the example reads it back, just to check that it's really there.
f = open("note.txt", "w")
f.write("Hi")
f.close()
print(open("note.txt").read())Prints
Hi
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Complete it so the file is created and written to.
3. Put the lines in order
Put the lines in order to save two days and then show the file.
4. Find the bug
This program should save each item on its own line. Which line has the bug?
5. Find the bug
This program should save the total in the file. Which line has the bug?
6. Predict the output
What does this code print?
7. Multiple choice
What happens if you open with
"w"a file that already had text in it?8. Predict the output
What does this code print?
9. Complete the code
Complete it so each day lands on its own row.
10. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.