Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

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:

Python
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:

Python
>>> 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
Avatar image for Cory

Cory on April 29, 2020

So on windows os all \n would have to be \r\n?

Avatar image for Ricky White

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.