Skip to the content

Appending

Python · Unit 17: Files

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. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Complete it so the file ends up with both items.

  3. 3. Find the bug

    This program should leave both visits in the file, one per line. Which line has the bug?

  4. 4. Put the lines in order

    Put the lines in order to leave both numbers in the file, one per line.

  5. 5. Predict the output

    What does this code print?

  6. 6. Complete the code

    Complete it so the program doesn't crash when the file isn't there.

  7. 7. Multiple choice

    What happens if you open with "a" a file that doesn't exist yet?

  8. 8. Find the case that fails

    read_all(name) should return the content of the file, or "" if the file doesn't exist. Only one.txt and two.txt were created. Which call breaks it?

  9. 9. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →