Appending to a File
Sometimes, you may want to append to a file or start writing at the end of an already populated file. You can do this by using the 'a'
character for the mode
argument:
with open('dog_breeds.txt', 'a') as a_writer:
a_writer.write('\nBeagle')
When you examine dog_breeds.txt
again, you’ll see that the beginning of the file is unchanged, and Beagle
is now added to the end of the file:
>>> with open('dog_breeds.txt', 'r') as reader:
>>> print(reader.read())
Pug
Jack Russell Terrier
English Springer Spaniel
German Shepherd
Staffordshire Bull Terrier
Cavalier King Charles Spaniel
Golden Retriever
West Highland White Terrier
Boxer
Border Terrier
Beagle
00:07
Opening a file in append mode using "a"
allows the adding of new content at the end of the existing file. This will allow us to add some lines of text to our already existing text file. As you can see here, the .write()
method and indeed .writelines()
are both available. It’s an open file, which is available for writing—just the place in which you’re writing is different. So now you can see this in action.
00:33
Here is a text file with lines 1, 2, and 3 already in it. And now back in our editor, let’s create the code that you’ve just seen. with open('text_file.txt')
, and now in append mode with the 'a'
, as file:
.
00:51
We can create some content
, here just a single string which we’re going to add with a newline character (\n
) on the end. And we can use the .write()
method and pass it content
to get that content written to the file. We can save that, execute it in the terminal,
01:18 and then looking in the text editor, we can see that after lines 1, 2, and 3, we have our new ending added.
Ricky White RP Team on April 29, 2020
Hi @Cory. No, \n
works fine on Windows, too. It’s what I always use.
Become a Member to join the conversation.
Cory on April 29, 2020
So on windows os all \n would have to be \r\n?