Python – Write to a text file (Append)

In this post we will be creating a Python script that will write to a text file. The script in this example will ask the user for input and then append this input to the text file, this means the same text file will constantly be updated with new lines of text.

See the snippet of code below which will write the input to a text file named ‘Output.txt’. We have added ‘\n’ so that each time we append to the text file, data is written to a new line.

with open("Ouput.txt", "a") as myfile:
    myfile.write("Hello\n")

After running the above our ‘Output.txt’ would be seen as.

Hello

Now we are running the code again but with a different message as seen below.

with open("Ouput.txt", "a") as myfile:
    myfile.write("How are you?\n")

After running the above our ‘Output.txt’ would be seen as.

Hello
How are you?

Leave a Reply