How to write to .txt files in Python 3

file, file-io, python, text

Solution

Open the file in append mode and write a new line (including a `\n` line separator):

with open(filename, 'a') as out:
    out.write(var + '\n')

This adds the line at the end of the file after all the other contents.

Problem

I have a `.txt` file in the same folder as this `.py` file and it has this in it: ``` cat\n dog\n rat\n cow\n ``` How can I save a var (var = 'ant') to the next line of the `.txt` file?

Original source