Rushy Panchal Rushy Panchal - 1 year ago 50
Python Question

How do you save each element of a list in a .txt file, one per line?

I have a list,

. I want to save it to a text (
) file, so that each element of the list is saved on a new line in the file. How can I do this?

This is what I have:

def save():
import pickle
pList = pickle.load(open('primes.pkl', 'rb'))
with open('primes.txt', 'wt') as output:
print "File saved."

However, the list is saved in just one line on the file.
I want it so every number (it solely contains integers) is saved on a new line.


pList=[5, 9, 2, -1, 0]
#Code to save it to file, each object on a new line

Desired Output:


How do I go about doing this?

Answer Source

Simply open your file, join your list with the desired delimiter, and print it out.

outfile = open("file_path", "w")
print >> outfile, "\n".join(str(i) for i in your_list)

Since the list contains integers, it's needed the conversion. (Thanks for the notification, Ashwini Chaudhary).

No need to create a temporary list, since the generator is iterated by the join method (Thanks, again, Ashwini Chaudhary).