append to a file in python

To append data to a file in python, you can use the built-in open() function with the "a" mode. The "a" mode stands for "append" and it allows you to add data to the end of a file.

Here's an example:

main.py
with open("myfile.txt", "a") as f:
    f.write("This is a new line.\n")
72 chars
3 lines

In this example, we open the file "myfile.txt" in append mode ("a") using a with statement. Then we use the write() method to add a new line at the end of the file.

The with statement is used to ensure that the file is properly closed after we're done with it, even if an error occurs.

You can also append multiple lines of data by calling write() method multiple times, or by passing a list of strings to the writelines() method.

main.py
with open("myfile.txt", "a") as f:
    lines_to_append = ["This is a new line.\n", "This is another new line.\n"]
    f.writelines(lines_to_append)
148 chars
4 lines

In this example, writelines() method is used to append multiple lines of text to myfile.txt.

gistlibby LogSnag