Appending

Appending

The mode "a" opens a file for appending: writes land at the end, and the existing content stays:

with open("log.txt", "w") as file:
    file.write("started\n")

with open("log.txt", "a") as file:
    file.write("saved\n")

with open("log.txt") as file:
    print(file.read())

Output:

started
saved

Had the second open used "w", the file would contain only saved — "w" empties, "a" extends. Like "w", "a" creates the file when it does not exist.

Appending suits logs and records: each run of the program adds to the history instead of overwriting it.

Exercise

  1. Define a function named log_event with two parameters: path and event.
  2. It appends one line to the file at path: the event text followed by a newline. Earlier lines must survive.

After log_event("log.txt", "login") and log_event("log.txt", "logout"), the file contains both lines in order.

Run your code to see the output, then press Submit.

Tests

import os
import unittest


class TestLogEvent(unittest.TestCase):
    def setUp(self):
        if os.path.exists("test_log.txt"):
            os.remove("test_log.txt")

    def test_two_events_appear_in_order(self):
        log_event("test_log.txt", "login")
        log_event("test_log.txt", "logout")
        with open("test_log.txt") as file:
            self.assertEqual(file.read(), "login\nlogout\n")

    def test_existing_content_survives(self):
        with open("test_log.txt", "w") as file:
            file.write("boot\n")
        log_event("test_log.txt", "login")
        with open("test_log.txt") as file:
            self.assertEqual(file.read(), "boot\nlogin\n")
def log_event(path, event):
    with open(path, "a") as file:
        file.write(event + "\n")


log_event("log.txt", "login")
log_event("log.txt", "logout")
with open("log.txt") as file:
    print(file.read())
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.