Writing a list to a file with Python

后端 未结 21 1835
孤街浪徒
孤街浪徒 2020-11-22 01:48

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

file.writelines([\"%s\\n\" % item  fo         


        
21条回答
  •  后悔当初
    2020-11-22 02:07

    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.

提交回复
热议问题