How to append text to a file in Python

Published on Aug. 22, 2023, 12:16 p.m.

To append text to a file in Python, you can use the open() function in “append” mode, which is denoted by “a” as the second argument. Here is an example:

with open("file.txt", "a") as file:
    file.write("This is a new line.")

In the example above, the “with” statement ensures that the file is properly closed after the write operation is completed. The “a” mode ensures that the text is appended to the end of the file, without overwriting any existing content. You can replace “file.txt” with the name of the file you want to append text to.

Note that if the file does not exist, it will be created automatically when you open it in “append” mode.

Tags:

related content