How to write to .txt files in Python 3

Viewed 111709

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?

2 Answers

Just to be complete on this question:

You can also use the print function.

with open(filename, 'a') as f:
    print(var, file=f)

The print function will automatically end each print with a newline (unless given an alternative ending in the call, for example print(var, file=f, end='') for no newlines).

Related