Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to .txt files in Python 3

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?

like image 997
Toby Smith Avatar asked Dec 06 '13 16:12

Toby Smith


People also ask

How do you write multiple lines in a text file in Python?

Python write multiple lines to file. To write multiple lines to a file in Python, use a with open() function and then the writelines() function. The writelines() method writes the items of a list to the file. The texts will be inserted depending on the file mode and stream position.


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

like image 65
Martijn Pieters Avatar answered Sep 19 '22 17:09

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

like image 42
Sebastian Avatar answered Sep 19 '22 17:09

Sebastian