Python – Append to File

Append to File in Python

In this tutorial, you will learn how to append content to an existing file in Python, with examples.

To append to a file in Python

  1. Open the file in append mode using open() built-in function
  2. Call the write() method on the file instance returned by open() function, and pass the content as argument to the write() method.

Now, let us go through some examples of appending content to a file in Python.


1. Append string to file in Python

In this example, we shall open a file named “data.txt” in append mode, and append the text in a string variable to the file, using write() method.

The existing content of data.txt is given below.

Python - Append to file - Input file data

Python Program

file_path = "data.txt"

content = "Hello World! This is some sample text."

with open(file_path, "a") as file:
    print(content, file=file)


Python - Append to File


In this tutorial of Python File Operations, we have seen how to write to a file in Python, with the help of example programs.

Related Tutorials

Code copied to clipboard successfully 👍