Python: Append Contents to a File

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 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!

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

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 seek method.

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.

Last Updated: July 9th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Jacob StopakAuthor

Jacob Stopak is a software developer and creator of InitialCommit.io - a site dedicated to teaching people how popular programs are coded. Its main project helps people learn Git at the code level.

Project

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup
Details
Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms