Writing a list to a file with Python

Is this the cleanest way to write a list to a file, since writelines() doesn't insert newline characters?

file.writelines(["%sn" % item  for item in list])

It seems like there would be a standard way...


EDIT Adding info from Thomas' comment

Don't forget to open the file first

thefile = open('test.txt', 'w')

I'd use a loop:

for item in thelist:
  thefile.write("%sn" % 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

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

To read it back:

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

最好的方法是:

outfile.write("n".join(itemlist))
链接地址: http://www.djcxy.com/p/68800.html

上一篇: C stdio无缓冲复用

下一篇: 用Python编写一个列表到一个文件