Sometimes, you don't want to replace the entire content of a file; you just want to add new information to the end of it. This is common for tasks like logging events, updating records, or simply adding more data over time without losing what was previously saved. The 'w'
mode for writing isn't suitable here because it erases the file's existing contents before writing anything new.
To add data to the end of an existing file, you open it in append mode. This is done by specifying 'a'
as the mode argument in the open()
function.
When you open a file in append mode:
'w'
mode.Let's see how this works. Suppose we have a file named log.txt
with the following content:
Event: System Start
Now, we want to add another event to this log. We can use append mode:
# log.txt already exists and contains "Event: System Start\n"
# Open log.txt in append mode ('a')
with open('log.txt', 'a') as f:
# Write a new line to the end of the file
# Note: We add '\n' to ensure the new entry starts on a new line
f.write("Event: User Login\n")
f.write("Event: Data Processed\n")
# The 'with' block automatically closes the file
# Let's verify the content
with open('log.txt', 'r') as f:
content = f.read()
print(content)
After running this code, the log.txt
file will now contain:
Event: System Start
Event: User Login
Event: Data Processed
Notice how the new lines were added after the original content. Also, observe that the write()
method, just like when using 'w'
mode, does not automatically add a newline character. If you want each piece of appended data to appear on its own line, you must explicitly include the newline character (\n
) in the string you pass to write()
.
Using append mode ('a'
) with the with
statement is the standard way to add information to the end of files, ensuring data integrity and proper resource management. It provides a simple mechanism for extending files without the risk of accidentally overwriting important existing data.
© 2025 ApX Machine Learning