The Python Oracle

Writing a list to a file with Python, with newlines

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2

--

Chapters
00:00 Writing A List To A File With Python, With Newlines
00:17 Answer 1 Score 453
00:38 Accepted Answer Score 1330
01:14 Answer 3 Score 503
01:38 Answer 4 Score 97
02:05 Thank you

--

Full question
https://stackoverflow.com/questions/8991...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #file #list #fileio #newline

#avk47



ACCEPTED ANSWER

Score 1330


Use a loop:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write(f"{line}\n")

For Python <3.6:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write("%s\n" % line)

For Python 2, one may also use:

with open('your_file.txt', 'w') as f:
    for line in lines:
        print >> f, line

If you're keen on a single function call, at least remove the square brackets [], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.




ANSWER 2

Score 503


What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?

If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list.

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

To read it back:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)



ANSWER 3

Score 453


Simpler is:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

To ensure that all items in the item list are strings, use a generator expression:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

Remember that itemlist takes up memory, so take care about the memory consumption.




ANSWER 4

Score 97


Yet another way. Serialize to json using simplejson (included as json in python 2.6):

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

If you examine output.txt:

[1, 2, 3, 4]

This is useful because the syntax is pythonic, it's human readable, and it can be read by other programs in other languages.