Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters?
file.writelines(["%s\n" % item for item in list])
It seems like there would be a standard way...
Thanks Josh
Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters?
file.writelines(["%s\n" % item for item in list])
It seems like there would be a standard way...
Thanks Josh
The best way is:
import os
outfile.write(os.linesep.join(itemlist))
Personally, I'd use a loop:
for item in thelist:
thefile.write("%s\n" % item)
or:
for item in thelist:
print>>thefile, item
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.
What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements, or are you just trying to serialize a list to disk for later use by the same python app. If the second case is it, you should be pickleing the list.
import pickle
pickle.dump(itemlist, outfile)
To read it back:
itemlist = pickle.load(infile)
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.