Writing a list to a file with Python

后端 未结 21 1785
孤街浪徒
孤街浪徒 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:04

    You can use a loop:

    with open('your_file.txt', 'w') as f:
        for item in my_list:
            f.write("%s\n" % item)
    

    In Python 2, you can also use

    with open('your_file.txt', 'w') as f:
        for item in my_list:
            print >> f, 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.

    0 讨论(0)
  • 2020-11-22 02:06

    Redirecting stdout to a file might also be useful for this purpose:

    from contextlib import redirect_stdout
    with open('test.txt', 'w') as f:
      with redirect_stdout(f):
         for i in range(mylst.size):
            print(mylst[i])
    
    0 讨论(0)
  • 2020-11-22 02:07

    The simpler way is:

    with open("outfile", "w") as outfile:
        outfile.write("\n".join(itemlist))
    

    You could ensure that all items in item list are strings using a generator expression:

    with open("outfile", "w") as outfile:
        outfile.write("\n".join(str(item) for item in itemlist))
    

    Remember that all itemlist list need to be in memory, so, take care about the memory consumption.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:07

    Because i'm lazy....

    import json
    a = [1,2,3]
    with open('test.txt', 'w') as f:
        f.write(json.dumps(a))
    
    #Now read the file back into a Python list object
    with open('test.txt', 'r') as f:
        a = json.loads(f.read())
    
    0 讨论(0)
  • 2020-11-22 02:07

    Let avg be the list, then:

    In [29]: a = n.array((avg))
    In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
    

    You can use %e or %s depending on your requirement.

    0 讨论(0)
提交回复
热议问题