How do I append to a file?
To append to a file in Python, you can use the "a"
mode of the built-in open()
function. This will open the file in append mode, which means that data will be added to the end of the file, rather than overwriting the file. Here's an example of how to append a string to a file:
# Open the file in append mode
with open("file.txt", "a") as f:
# Write the string to the file
f.write("This is a new line of text\n")
Watch a video course
Python - The Practical Guide
You can also use the writelines()
method to write a list of strings to the file at once:
lines = ["line 1\n", "line 2\n", "line 3\n"]
# Open the file in append mode
with open("file.txt", "a") as f:
# Write the lines to the file
f.writelines(lines)
It's generally good practice to use the with
statement when working with files, as it ensures that the file is closed properly after you're done with it.