How to append data to a file in Python

In this tutorial, we are going to learn how to append data to a file in Python. To do this we are going to use open() method to open the file in append mode and write() method to write the data to the file. Let’s see how.

As we know we first use the open() method to ready the file for any operation. To append some data to the file, we open the file in ‘a’ or ‘ab’ mode. We use ‘a’ to open the file for appending data and ‘ab’ to open the file in binary format for appending data. We can also use ‘a+’ to do this. Using the ‘+’ sign indicates that a new file will be created if the given file does not exist. Also, in ‘a+’ mode we can use seek() method. To know about seek() method see this: File operations for tell() and seek() functions in Python

After opening the file, we use the write() method to write additional texts in the file as you can see in the given examples. Once we are done with the file we use the close() method to finally close the file.

Let’s understand this with an example program.

First, run the below code to create a text file.

#creatinng a text file
f = open("CodeSpeedy.txt", "w+")

The above code creates a file with the name “Codespeedy.txt” and the content ”CodeSpeedy”.

Now let’s write a python program to write ”CodeSpeedy again” to the same file.

Have a look at the below code.

#opening the file in append mode
f = open("CodeSpeedy.txt", "a")
#appending data
f.write("CodeSpeedy again\n")
#closing the file

When we run the above code, it modifies the content of the text file as given below.

CodeSpeedy again

We can see that we are able to append data to a file in Python successfully.

We can also use ‘with’ for the above operation. See the code below.

with open("CodeSpeedy.txt", "a") as f:
    f.write("CodeSpeedy again\n")

After running the above code, the content of the text file is modified again and it becomes:

CodeSpeedy again
CodeSpeedy again

Note that we have not used the close() method in the above code.

Leave a Reply

Your email address will not be published. Required fields are marked *