How do I append to a file in Python?

Better Stack Team
Updated on February 3, 2023

To append to a file in Python, you can use the "a" mode in the open() function. This will open the file in append mode, which means that you can write new data at the end of the file.

Here is an example of how to use the "a" mode to append to a file:

# Open the file in append mode
with open("filename.txt", "a") as file:
    # Write the new data to the file
    file.write("This is new data that is being appended to the file.")

You can also use the "a" mode to create a new file if the file does not already exist. If the file does not exist, it will be created and you can then write data to it.

Keep in mind that the "a" mode will not overwrite any existing data in the file. It will only add new data to the end of the file. If you want to overwrite the existing data in the file, you can use the "w" mode instead.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack