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")
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 start at the very beginning and overwrite the existing content.
Now we can write content to the file like this:
f.write("\nIt's good to have been born!") f.close()
Remember to call the
close method after writing to files so that it doesn't remain locked after the program exits and to ensure that any buffered content in memory gets written to the file.
Here is what the file looks like after we append to it:
$ cat ./helloworld.txt Hello world! It's good to have been born!
One final note is that if we add a "+" to the mode argument of the
open method, we can open the file for both appending and reading. This will enable both reading and writing to the file. Without the "+" an
IOError exception will occur if we try and read from the file. By default both reading and writing will occur at the end of the file, but this can be changed at any time using the
Here are the commands to achieve this (note that we use the
flush method to ensure the new content is written to the file before we try to read it back):
f = open("./helloworld.txt", "a+") f.write("I am grateful.") f.flush() f.seek(0) content = f.read() print content f.close()
And here is what the final file looks like:
$ cat ./helloworld.txt Hello world! It's good to have been born! I am grateful.
About the Author
This article was written by Jacob Stopak, a software consultant and developer with passion for helping others improve their lives through code. Jacob is the creator of Initial Commit - a site dedicated to helping curious developers learn how their favorite programs are coded. Its featured project helps people learn Git at the code level.Reference: stackabuse.com