The Python Oracle

Writing a list to a file with Python, with newlines

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:23 Accepted answer (Score 1239)
01:10 Answer 2 (Score 486)
01:41 Answer 3 (Score 424)
02:07 Answer 4 (Score 105)
02:44 Thank you

--

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

Answer 1 links:
[pickleing]: http://docs.python.org/library/pickle.ht...

Answer 3 links:
[UNIX best practice]: https://stackoverflow.com/questions/7296...

--

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.