Append Text to a File in Python

  1. file.write to Append Text to a File With a Mode
  2. Add Optional file Parameter to the print Function in Python 3
  3. Add New Line in Appending Text to a File

This tutorial article will introduce how to append text to a file in Python.

file.write to Append Text to a File With a Mode

You could open the file in a or a+ mode if you want to append text to a file.

destFile = r"C:\Test\Test.txt"
with open(destFile, 'a') as f:
    f.write("some appended text")

The code above appends the text some appended text next to the last character in the file. For example, if the file ends with this is the last sentence, then it becomes this is the last sentencesome appended text after appending.

It will create the file if the file doesn’t exist in the given path.

Add Optional file Parameter to the print Function in Python 3

In Python 3, you could print the text to the file with the optional file parameter enabled.

destFile = r"C:\Test\Test.txt"
with open(destFile, 'a') as f:
    print("The result will be {}".format(Result), file=f)

Add New Line in Appending Text to a File

If you prefer to add the text in the new line, you need to add the carriage break \r\n after the appended text to guarantee the next appended text will be added to the new line.

destFile = r"C:\Test\Test.txt"
with open(destFile, 'a') as f:
    f.write("the first appended text\r\n")
    f.write("the second appended text\r\n")
    f.write("the third appended text\r\n")
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python File

  • Copy a File in Python
  • Read Specific Lines From a File in Python