Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

text

list

io

I have a list, pList. I want to save it to a text (.txt) 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:
      output.write(str(pList))
    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.

Example:

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

Desired Output:

5
9
2
-1
0

How do I go about doing this?

like image 515
Rushy Panchal Avatar asked Nov 17 '12 19:11

Rushy Panchal


People also ask

How do I make a list in a text file?

Method 2: write in a Text file In Python using writelines() The file is opened with the open() method in w mode within the with block, the argument will write text to an existing text file with the help of readlines().


Video Answer


2 Answers

You can use map with str here:

pList = [5, 9, 2, -1, 0]
with open("data.txt", 'w') as f:
    f.write("\n".join(map(str, pList)))
like image 110
Ashwini Chaudhary Avatar answered Oct 19 '22 23:10

Ashwini Chaudhary


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)
outfile.close()

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

like image 34
Rubens Avatar answered Oct 20 '22 00:10

Rubens