Appending
Python · Unit 17: Files
- Full plan
- Python
- 9 exercises
Mode "a" (for append) writes at the end without erasing what was there.
"w" always starts from zero; "a" carries on.
with open("log.txt", "w") as f:
f.write("one\n")
with open("log.txt", "a") as f:
f.write("two\n")
print(open("log.txt").read())Prints
one two
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 ends up with both items.
3. Find the bug
This program should leave both visits in the file, one per line. Which line has the bug?
4. Put the lines in order
Put the lines in order to leave both numbers in the file, one per line.
5. Predict the output
What does this code print?
6. Complete the code
Complete it so the program doesn't crash when the file isn't there.
7. Multiple choice
What happens if you open with
"a"a file that doesn't exist yet?8. Find the case that fails
read_all(name)should return the content of the file, or""if the file doesn't exist. Onlyone.txtandtwo.txtwere created. Which call breaks it?9. 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.