How to write to .txt files in Python 3

Question:

I have a .txt file in the same folder as this .py file and it has this in it:

catn
dogn
ratn
cown

How can I save a var (var = ‘ant’) to the next line of the .txt file?

Asked By: Toby Smith

||

Answers:

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.

Answered By: Martijn Pieters

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).

Answered By: Sebastian
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.