Python: Append Contents to a File


In this article, we’ll examine how to append content to an existing file using Python.

Let’s say we have a file called helloworld.txt containing the text “Hello world!” and it is sitting in our current working directory on a Unix file system:

$ cat ./helloworld.txt
Hello world!

Now assume we want to append the additional text “It’s good to have been born!” to the end of this file from a Python program.

The first step is to obtain a reference to the file from our program. This can be done with the built-in open method, using the file path/name as the first argument and the mode as the second argument, as follows:

f = open("./helloworld.txt", "a")

The variable f now holds a reference to a file object that we can use to write to the end of the file. If the file didn’t already exist, it will be created. Note that the second argument “a” specified the mode to open the file with, in this case “Append” mode. This sets the writing position to the end of the file.

If we had used the “w” (Write mode), then anything we write to the file will

To finish reading, please visit source site