10

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?

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94

3 Answers3

15

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)))
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
11

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

Rubens
  • 14,478
  • 11
  • 63
  • 92
0

Refer to this answer to get a function that adds an item to a new line for the given file

https://stackoverflow.com/a/13203890/325499

def addToFile(file, what):
    f = open(file, 'a').write(what+"\n") 

So for your question, instead of just passing the list to the file, you will need to iterate through the list.

for item in pList:
    addToFile(item)
Community
  • 1
  • 1
Kartik
  • 9,463
  • 9
  • 48
  • 52
  • 1
    I don't think there's a need of defining such extra function, and opening and closing a file for every item of the list will cost too many I/O operations. – Ashwini Chaudhary Nov 17 '12 at 19:50