Append a Line to a Log File in Python
Append a line to a file using a context manager and Path.open().
Python code
14 linesfrom 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
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
- Use `with open(filepath, 'a') as f: f.write(message + '\n')` with the built-in open()
- 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
More from Files & data
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
- Build a Personal Work Hours Tracker in Python medium
Keep learning
Related tutorials and quizzes for this topic.