Append a Line to a Log File in Python

Append a line to a file using a context manager and Path.open().

Easy Python 3.4+ Aug 9, 2026 Files & data 18 views 0 copies

Python code

14 lines
Python 3.4+
from pathlib import Path

def append_to_log(filepath, message):
    with Path(filepath).open("a") as log_file:
        log_file.write(f"{message}\n")

if __name__ == "__main__":
    log_path = "log.txt"
    append_to_log(log_path, "First entry")
    append_to_log(log_path, "Second entry")
    
    # Verify contents
    with Path(log_path).open("r") as log_file:
        print(log_file.read(), end="")

Output

stdout
First entry
Second entry

How it works

The Path.open method opens the file and returns a file object. The with statement binds that object to log_file and ensures it is automatically closed when the block exits, even if an error occurs. Opening the file in "a" (append) mode positions the write pointer at the end of the file, so each call adds a new line without overwriting existing content. The f"{message}\n" string literal formats the message with a newline. Running the script first appends two lines, then reads the file and prints its contents, which shows both lines in order.

Common mistakes

  • Using "w" instead of "a" which overwrites the file each time
  • Forgetting to add a newline (\n) so lines concatenate
  • Not using a context manager and calling close() manually, risking resource leaks

Variations

  1. Use `with open(filepath, 'a') as f: f.write(message + '\n')` with the built-in open()
  2. Use `logging.basicConfig(filename='app.log', level=logging.INFO)` for structured logging

Real-world use cases

  • Appending user activity events to an audit trail file in a web application.
  • Adding timestamped entries to a custom text log in a long-running cron job.
  • Recording each API request to a plain-text log for later manual inspection.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.