【问题标题】:Writing a list to a file with Python使用 Python 将列表写入文件
【发布时间】:2025-11-23 10:30:01
【问题描述】:

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

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

好像会有一个标准的方法...

【问题讨论】:

  • 请注意writelines 不会添加换行符,因为它反映了readlines,而readlines 也不会删除它们。
  • 它在 json 和 pickle 之间。阅读所有相关信息 - *.com/questions/27745500/…

标签: python file list file-io newline


【解决方案1】:

你可以使用循环:

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 >> f, item

如果您热衷于单个函数调用,请至少删除方括号 [],以便一次生成一个要打印的字符串(一个 genexp 而不是一个 listcomp)——没有理由占用实现整个字符串列表所需的所有内存。

【讨论】:

  • 这不是很复杂,但是为什么不直接使用pickle或者json这样就不用担心序列化和反序列化了呢?
  • 例如,因为您想要一个易于阅读、编辑等的输出文本文件,每行一个项目。几乎不是一个罕见的愿望;-)。
  • 这将在最后写一个额外的换行符...而不是循环,你可以写thefile.write('\n'.join(thelist))
  • 我会添加:“小心列表数据类型”。我得到了一些奇怪的结果,也许这可以帮助某人:thefile.write(str(item) + "\n")
  • 对 python 3.7'ish f.write(f'{item}\n') 稍微简单一点
【解决方案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)

【讨论】:

  • +1 - Python 内置了序列化,为什么还要重新发明*?
  • +1 - outfile 类似于:open( "save.p", "wb" ) infile 类似于:open( "save.p", "rb" )
  • 问题是列表必须适合内存。如果不是这种情况,逐行确实是一种可能的策略(或者使用*.com/questions/7180212/… 中的一些替代方法)
  • 在 Python 2 中,如果您收到“ValueError: insecure string pickle”,则在读取 pickle 时使用 'r' 而不是 'rb'
  • @serafeim:不; with: 块将在继续执行 with 块之外的下一条语句之前关闭文件。
【解决方案3】:

更简单的方法是:

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

您可以使用生成器表达式确保项目列表中的所有项目都是字符串:

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

请记住,所有itemlist 列表都需要在内存中,因此,请注意内存消耗。

【讨论】:

  • 没有尾随换行符,与循环相比使用了 2 倍的空间。
  • 当然,首先想到的问题是 OP 是否需要它以换行符结尾以及空间量是否重要。你知道他们怎么说过早的优化。
  • 一个缺点:这会在写出任何内容之前在内存中构造文件的全部内容,因此峰值内存使用率可能很高。
  • 我永远无法让它工作。我收到此错误:“text = '\n'.join(namelist) + '\n' TypeError: sequence item 0: expected string, list found”
  • 您必须确保 'namelist' 中的所有元素都是字符串。
【解决方案4】:

使用 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

从 Python 3.6 开始,"{}\n".format(item) 可以替换为 f 字符串:f"{item}\n"

【讨论】:

  • 我不想为最后一项添加“\n”,怎么办?不想要 if 条件
  • @pyd 将 for 循环替换为 file_handler.write("\n".join(str(item) for item in the_list))
【解决方案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]

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

【讨论】:

  • 这对于多行字符串要好得多
【解决方案6】:

我认为探索使用 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)

【讨论】:

    【解决方案7】:

    因为我很懒......

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

    【讨论】:

    • 列表是 json 可序列化的吗?
    • 是的,确实如此!
    • 导入 json ; test_list = [1,2,3]; list_as_a_string = json.dumps(test_list); #list_as_a_string 现在是字符串 '[1,2,3]'
    • 我正在这样做 with open ('Sp1.txt', 'a') as outfile: json.dump (sp1_segments, outfile) logger.info ("Saved sp_1 segments") ;问题是我的程序运行了三次,并且三次运行的结果被混搭了。有什么方法可以添加 1-2 个空行,以便每次运行的结果都清晰可见?
    • 绝对!你能改成json.dump(sp1_segments + "\n\n", outfile)吗?
    【解决方案8】:

    用逗号分隔值将列表序列化为文本文件

    mylist = dir()
    with open('filename.txt','w') as f:
        f.write( ','.join( mylist ) )
    

    【讨论】:

      【解决方案9】:

      一般情况

      以下是 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

      【讨论】:

        【解决方案10】:
        file.write('\n'.join(list))
        

        【讨论】:

        • 请注意,这将要求文件以文本形式打开才能真正与平台无关。
        • 如何获得file 变量?
        【解决方案11】:

        在 python>3 中,您可以使用 print* 进行参数解包:

        with open("fout.txt", "w") as fout:
            print(*my_list, sep="\n", file=fout)
        

        【讨论】:

          【解决方案12】:
          with open ("test.txt","w")as fp:
             for line in list12:
                 fp.write(line+"\n")
          

          【讨论】:

            【解决方案13】:

            如果你在python3上也可以使用打印功能如下。

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

            【讨论】:

            • 是不是只在 myfile.txt 中放了一行,类似于:['a','b','c'] 而不是在每一行都写上 a,b,c。
            【解决方案14】:

            使用numpy.savetxt 也是一种选择:

            import numpy as np
            
            np.savetxt('list.txt', list, delimiter="\n", fmt="%s")
            

            【讨论】:

              【解决方案15】:

              你为什么不试试

              file.write(str(list))
              

              【讨论】:

                【解决方案16】:

                此逻辑将首先将列表中的项目转换为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 
                

                【讨论】:

                  【解决方案17】:

                  您还可以通过以下方式:

                  例子:

                  my_list=[1,2,3,4,5,"abc","def"]
                  with open('your_file.txt', 'w') as file:
                      for item in my_list:
                          file.write("%s\n" % item)
                  

                  输出:

                  your_file.txt 中的项目保存如下:

                  1
                  
                  2
                  
                  3
                  
                  4
                  
                  5
                  
                  abc
                  
                  def
                  

                  您的脚本也按上述方式保存。

                  否则你可以用pickle

                  import pickle
                  my_list=[1,2,3,4,5,"abc","def"]
                  #to write
                  with open('your_file.txt', 'wb') as file:
                      pickle.dump(my_list, file)
                  #to read
                  with open ('your_file.txt', 'rb') as file:
                      Outlist = pickle.load(file)
                  print(Outlist)
                  

                  输出: [1, 2, 3, 4, 5, 'abc', 'def']

                  当我们加载我们可以读取的列表时,它会保存与列表相同的列表。

                  也可以通过simplejson 与上述输出相同

                  import simplejson as sj
                  my_list=[1,2,3,4,5,"abc","def"]
                  #To write
                  with open('your_file.txt', 'w') as file:
                      sj.dump(my_list, file)
                  
                  #To save
                  with open('your_file.txt', 'r') as file:
                      mlist=sj.load(file)
                  print(mlist)
                  

                  【讨论】:

                  • 感谢您添加输出,非常有帮助
                  【解决方案18】:

                  简单地说:

                  with open("text.txt", 'w') as file:
                      file.write('\n'.join(yourList))
                  

                  【讨论】:

                    【解决方案19】:

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

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

                    【讨论】:

                      【解决方案20】:

                      将标准输出重定向到文件也可能对此有用:

                      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])
                      

                      【讨论】:

                        【解决方案21】:

                        我建议这个解决方案。

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

                        【讨论】:

                          【解决方案22】:

                          我最近发现 Path 很有用。帮助我绕过with open('file') as f 然后写入文件。希望这对某人有用:)。

                          from pathlib import Path
                          import json
                          a = [[1,2,3],[4,5,6]]
                          # write
                          Path("file.json").write_text(json.dumps(a))
                          # read
                          json.loads(Path("file.json").read_text())
                          

                          【讨论】:

                            【解决方案23】:

                            我认为您正在寻找这样的答案。

                            f = open('output.txt','w')
                            list = [3, 15.2123, 118.3432, 98.2276, 118.0043]
                            f.write('a= {:>3d}, b= {:>8.4f}, c= {:>8.4f}, d= {:>8.4f}, e= 
                            {:>8.4f}\n'.format(*list))
                            f.close()
                            

                            【讨论】:

                              【解决方案24】:

                              Python3中可以使用这个循环

                              with open('your_file.txt', 'w') as f:
                                  for item in list:
                                      f.print("", item)
                              

                              【讨论】:

                                【解决方案25】:

                                设 avg 为列表,则:

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

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

                                【讨论】:

                                  【解决方案26】:
                                  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
                                  

                                  它是如何工作的: 首先,使用内置的 open 函数打开一个文件并指定文件名 文件和我们想要打开文件的模式。该模式可以是 读取模式 ('r')、写入模式 ('w') 或附加模式 ('a')。我们也可以指定 无论我们是在文本模式('t')还是二进制模式下读取、写入或附加 模式('b')。实际上还有更多可用的模式和帮助(打开) 将为您提供有关它们的更多详细信息。默认情况下,open() 将文件视为 成为一个 't'ext 文件并以 'r'ead 模式打开它。 在我们的示例中,我们首先以 write text 模式打开文件并使用 write 文件对象的方法写入文件,然后我们最终关闭文件。

                                  以上示例来自 Swaroop C H 的《A Byte of Python》一书。 swaroopch.com

                                  【讨论】:

                                  • 这会将字符串写入文件,而不是 OP 要求的(字符串)列表