tags:

views:

2963

answers:

5

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

+1  A: 

The best way is:

import os

outfile.write(os.linesep.join(itemlist))
osantana
No trailing newline, uses 2x space compared to the loop.
Dave
Of course the first question that springs to mind is whether or not the OP needs it to end in a newline and whether or not the amount of space matters. You know what they say about premature optimizations.
Jason Baker
+8  A: 

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.

Alex Martelli
#2 is the most idiomatic IMHO.
Dave
This isn't terribly complex, but why not just use pickle or json so that you don't have to worry about the serialization and deserialization?
Jason Baker
For example because you want an output text file that can be easily read, edited, etc, with one item per line. Hardly a rare desire;-).
Alex Martelli
+1  A: 

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)
TokenMacGuy
+1 - Why reinvent the wheel when Python has serialization built in?
Jason Baker
+1  A: 

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.

Jason Baker
+1  A: 
file.write('\n'.join(list))
mtasic
One should note that this will require that the file be opened as text to be truly platform-neutral.
Jason Baker