Appending to a File in Python
Now that you're familiar with the basic syntax for creating files, writing to files and also how to search for certain types of files, now we can actually see how we can extend this knowledge and see how we can add to a preexisting file.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

If you remember back to our initial guide, when we created a new file, every time we ran that script, it overrode all of the content that was already there and sometimes that's what you wanna do for things like temporary files but in most scenarios, you usually want to append to a file and that's what we're going to do and we're gonna build a logging function through that.

So I'm gonna start by importing a couple of dependencies here at the top. I have a Python file open and I'm gonna import the datetime library. And then I'm gonna say from time I want to import sleep.

import datetime
from time import sleep

And you'll see here in a second why I'm importing these. These are not needed in order to append to files, however, they are going to help us to test to make sure that this is working. So now I'm going to create a range, so I'll say for i in range and we want this to be a small range so I'm gonna say for a range of five, inside of here, inside of this code block, I want to first build a file.

So I'll declare a variable called file_builder like we did earlier and I'm gonna set this equal to open and then I want to create this new file. So as a string, I'll say logger.txt and that's gonna be the first argument. Now, the second argument, this is where the magic happens. This is how you can append to a file.

So the second argument is a string and I'm gonna say a plus and end the string and then close out that method call to open. Also, give us a little bit of room here and now we can write to the file. So here I'll say I want to write to the file_builder and so I'm gonna call my write function just like we did before and I'm gonna this time, I'm going to use some string literals.

So I'll say write and then with an f for being able to format this, I'm going to say datetime which is what we brought in so I'll say datetime.datetime.now. So I'm just gonna call that function and then close off those curly brackets and then add a backspace n and then close off the string and then end the write function call.

import datetime
from time import sleep

for i in range(5):
    file_builder = open("logger.txt", "a+")
    file_builder.write(f'{datetime.datetime.now()}\n')

So what this is doing here is this is getting us our datetime object and this function, so I can call datetime the library, then I'll call datetime the module inside of that library and then I'm gonna call the function now.

What that does is it simply brings in the current date as a timestamp and you can test this out inside of the Python shell here. So you could say import datetime and then say datetime.datetime.now and then see that that brings in a datetime object and that's exactly what we want.

large

The reason why I want to bring in this datetime object is one so that you can learn how to use it but also so that you can see that each one of these entries is gonna be different.

So after that, I'll say file_builder.close, call that function, let's add some debugging output. So I'll say print file created, close that off and then this is where we're gonna call sleep. The reason why I'm calling sleep here and I'm going to have it sleep for one second for each one of these loop iterations and that's why we brought in the sleep library up top and the reason why I'm doing that is because I want a different datetime stamp for each one of these elements just to prove that they are different.

So now I'm gonna open up the file system so that we can see all the files and then I'll come down and actually run the code. So I have pip env shell running right now, so I'll say python, this is in the file-section/01_appending_to_file and you can see that our output is working so it's giving us those file created print statements.

large

Now if you come to the file system and hit refresh, you can see we have a new file here called logger.

large

Now, notice, even though I didn't pass in any kind of path, I just gave a name right here, you might think that this file would be created in the same directory as the current script that we're running, this for loop.

But instead, it's not in the file section as you can see. It's actually at the root of the application and so that is something very important to understand because wherever you're running your code from, in this case, I am at the root of the application, I'm at the root of this code repository here, that is where that file will be created.

Now, you could always pass in a path. So I could say file-section/logger and that would also work. It would put it inside of the file section directory. Because that can be a little bit confusing, I want you to make sure that you're aware of that.

So if I open this up, you can see that we have created a logger file and it has five entries and you can also see that these times are different because we called sleep. So we have five seconds, six seconds, seven, eight, and nine.

large

Now, let's see what happens if we run this again, so I'm gonna run Python and run the exact same file. It's going to add these lines but now instead of replacing all of the contents in the file, now if we come back, I'm going to first just switch files just so we can refresh it, go back to the logger and now you can see that that is working perfectly.

large

The script did not override the first five entries, it simply added on, it appended to the current file. So this is where ever you have a situation where you have something such as a log file or any kind of file that you simply want to tack onto, then using the a+ flag is the way to do.

So just in review, we imported the datetime library and the sleep library just to give us some data where we could tell the difference with the data points. From there, we created a range of going from one to five, and then we created a file_builder object here where we created a new file and the key difference here was instead just of writing to the file, we use the a+ flag which allows us to append to it. We wrote to the file, closed it and then we repeated that every second for five times, and that worked. So great job if you went through that, you now know how to append data to a file in Python.

Code

import datetime
from time import sleep

for i in range(5):
    file_builder = open("logger.txt", "a+")
    file_builder.write(f'{datetime.datetime.now()}\n')
    file_builder.close()

    print("file created")

    sleep(1)