Python | Working with Files | Writing to a Text File

To write to a text file all you have to do is to open the file in writing mode. Be aware that the writing mode will erase the content of the file. You should open a file in append mode so the content you will add to the file will be added at the end without erasing anything.

Let’s use the same example.txt as testing file and let’s take a look at the following code.

variableOne = open('example.txt','a')

variableOne.write('This is the fourth line')
variableOne.write('\nThis is the fifth line')


If you run this code in terminal then the terminal won’t show you anything out of ordinary. But if you open the file example.txt you will have five lines of text, the three we had before and the two new lines from our code.

Writing to a file in Python

Note that when you open a file in append mode you can not read from the file. That is the reason we cant use the print() function in this particularly example.

Also notice the escape character \n which will add a new line to the text file otherwise we will have something like This is the fourth lineThis is the fifth line.

Leave a Reply