首页 文章

使用Python将列表写入文件

提问于
浏览
444

这是将列表写入文件最干净的方法,因为 writelines() 不插入换行符吗?

file.writelines(["%s\n" % item  for item in list])

似乎有一种标准方式......

17 回答

  • -2

    你打算怎么处理这个档案?此文件是否适用于人类或具有明确互操作性要求的其他程序,或者您只是尝试将列表序列化到磁盘以供以后由同一个python应用程序使用 . 如果是第二种情况,那么你应该是pickleing列表 .

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

    读回来:

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

    你可以使用循环:

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

    在Python 2中,您也可以使用

    with open('your_file.txt', 'w') as f:
        for item in my_list:
            print >> thefile, item
    

    如果您热衷于单个函数调用,至少删除方括号 [] ,以便一次一个地创建一个字符串(genexp而不是listcomp) - 没有理由占用所有内存需要实现整个字符串列表 .

  • 211

    使用逗号sepparated值将列表序列化为文本文件

    mylist = dir()
    with open('filename.txt','w') as f:
        f.write( ','.join( mylist ) )
    
  • 17
    file.write('\n'.join(list))
    
  • 79
    with open ("test.txt","w")as fp:
       for line in list12:
           fp.write(line+"\n")
    
  • 13

    迭代和添加换行符的另一种方法:

    for item in items:
        filewriter.write(f"{item}" + "\n")
    
  • -2

    我认为探索使用genexp的好处会很有趣,所以这是我的看法 .

    问题中的示例使用方括号来创建临时列表,因此等效于:

    file.writelines( list( "%s\n" % item for item in list ) )
    

    哪个不必要地构造了将要写出的所有行的临时列表,这可能会消耗大量内存,具体取决于列表的大小以及 str(item) 的输出有多详细 .

    删除方括号(相当于删除上面的包装 list() 调用)将改为将临时generator传递给 file.writelines()

    file.writelines( "%s\n" % item for item in list )
    

    此生成器将按需创建 item 对象的换行符(即,当它们被写出时) . 这很好,原因有两个:

    • 内存开销很小,即使对于非常大的列表也是如此

    • 如果 str(item) 很慢,则在处理每个项目时文件中都会有明显的进展


    这可以避免内存问题,例如:

    In [1]: import os
    
    In [2]: f = file(os.devnull, "w")
    
    In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
    1 loops, best of 3: 385 ms per loop
    
    In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
    ERROR: Internal Python error in the inspect module.
    Below is the traceback from this internal error.
    
    Traceback (most recent call last):
    ...
    MemoryError
    

    (我通过使用 ulimit -v 102400 将Python的最大虚拟内存限制为~100MB来触发此错误) .

    将内存使用放在一边,这种方法实际上并不比原始方法快:

    In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
    1 loops, best of 3: 370 ms per loop
    
    In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
    1 loops, best of 3: 360 ms per loop
    

    (Linux上的Python 2.6.2)

  • 607

    如果你在python3上,你也可以使用print函数,如下所示 .

    f = open("myfile.txt","wb")
    print(mylist, file=f)
    
  • 5

    还有另一种方式 . 使用simplejson(在python 2.6中包含为json)序列化为json:

    >>> import simplejson
    >>> f = open('output.txt', 'w')
    >>> simplejson.dump([1,2,3,4], f)
    >>> f.close()
    

    如果你检查output.txt:

    [1,2,3,4]

    这很有用,因为语法是pythonic,它是人类可读的,并且可以被其他语言的其他程序读取 .

  • 2

    使用 Python 3Python 2.6+ 语法:

    with open(filepath, 'w') as file_handler:
        for item in the_list:
            file_handler.write("{}\n".format(item))
    

    这与平台无关 . 它还使用换行符终止最后一行,这是一个UNIX best practice .

  • 77

    让avg成为列表,然后:

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

    您可以根据需要使用 %e%s .

  • 7

    此逻辑将首先将列表中的项目转换为 string(str) . 有时列表中包含一个元组

    alist = [(i12,tiger), 
    (113,lion)]
    

    该逻辑将写入一个新行中的每个元组 . 我们以后可以在读取文件时加载每个元组时使用 eval

    outfile = open('outfile.txt', 'w') # open a file in write mode
    for item in list_to_persistence:    # iterate over the list items
       outfile.write(str(item) + '\n') # write to the file
    outfile.close()   # close the file
    
  • -1

    一般

    以下是 writelines() 方法的语法

    fileObject.writelines( sequence )
    

    示例

    #!/usr/bin/python
    
    # Open a file
    fo = open("foo.txt", "rw+")
    seq = ["This is 6th line\n", "This is 7th line"]
    
    # Write sequence of lines at the end of the file.
    line = fo.writelines( seq )
    
    # Close opend file
    fo.close()
    

    参考

    http://www.tutorialspoint.com/python/file_writelines.htm

  • 269

    最好的方法是:

    outfile.write("\n".join(itemlist))
    
  • 1

    因为我很懒....

    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())
    
  • 12

    你为什么不试试

    file.write(str(list))
    
  • 31
    poem = '''\
    Programming is fun
    When the work is done
    if you wanna make your work also fun:
    use Python!
    '''
    f = open('poem.txt', 'w') # open for 'w'riting
    f.write(poem) # write text to file
    f.close() # close the file
    

    工作原理:首先,使用内置的打开功能打开文件,并指定文件的名称和我们想要打开文件的模式 . 模式可以是读模式('r'),写模式('w')或附加模式('a') . 我们还可以指定我们是以文本模式('t')还是二进制模式('b')进行读,写或追加 . 实际上还有更多模式可供使用,帮助(开放)将为您提供更多有关它们的详细信息 . 默认情况下,open()认为文件是't'ext文件,并在'r'ead模式下打开它 . 在我们的示例中,我们首先在写文本模式下打开文件,并使用文件对象的write方法写入文件,然后我们最终关闭文件 .

    The above example is from the book "A Byte of Python" by Swaroop C H. swaroopch.com

相关问题