How to Append Text to File in Python? Examples


Python - Append Text to File

To append text to an existing file in Python, follow these steps.

  1. Open file in append mode a+.
  2. Write or append the text to the file.
  3. Close the file.

Example 1: Concatenate or Append Text to File

In the following example, we have an existing file data.txt with some text. We will append some more text to the existing data by following the steps said above.

Python Program

fin = open("data.txt", "a")

fin.write('\nThis is newly appended text.');

fin.close()

Input Text File - data.txt before running the python example

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

Text File with Appended Text after running the python example

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.
This is newly appended text.

Example 2: Append Text to File in Text Mode

You can handle the file either in text or binary mode. By default, the file will be handled in text mode. In the following example, we will handle the file explicitly in text mode by appending "t" to the append mode "a".

Python Program

fin = open("data.txt", "at")

fin.write('\nThis is newly appended text.');

fin.close()

Summary

In this tutorial of Python Examples, we learned how to append text to a file in Python, with the help of example programs.