Write a function that appends a new line to an existing log file, without erasing what's already there.
append_log_line(path, line)
Append "\n" + line to the end of the file at path, and return "done".
Given a file at path containing "first line", after append_log_line(path, "second line"), the file contains "first line\nsecond line".
def append_log_line(path, line):
with open(path, "a") as f:
f.write("\n" + line)
return "done"
This is exactly the mode distinction from the file I/O introduction lesson, put to use. "w" mode would truncate the file the instant it's opened — you'd lose "first line" entirely before ever writing anything. "a" mode instead opens the file positioned at its end, so anything you write() gets added after the existing content, leaving it untouched.
The "\n" + line is the other detail that matters: write() never adds a newline on its own (unlike print()). Without it, appending "second line" directly would produce "first linesecond line" — jammed together with no line break. Prepending "\n" ensures the new line actually starts on its own line.
def append_log_line(path, line):
with open(path, "a") as f:
f.write("\n" + line)
return "done"
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.