使用Python将列表写入文件

Jos*_*erg 601 python file-io newline file list

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

file.writelines(["%s\n" % item  for item in list])
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lli 816

你可以使用一个循环:

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

在Python 2中,您也可以使用

with open('your_file.txt', 'w') as f:
    for item in my_list:
        print >> f, item
Run Code Online (Sandbox Code Playgroud)

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

  • 例如,因为您需要一个可以轻松读取,编辑等的输出文本文件,每行一个项目.几乎不是一种罕见的欲望;-). (75认同)
  • 这将在结尾写一个额外的换行符...而不是循环,你可以只写`thefile.write('\n'.join(thelist))` (8认同)
  • 这不是非常复杂,但为什么不使用pickle或json以便您不必担心序列化和反序列化? (7认同)
  • 我会添加:“请小心列表数据类型”。我得到了一些奇怪的结果,也许这可以对某人有所帮助:`thefile.write(str(item)+“ \ n”)` (3认同)
  • 对于 python 3.7'ish `f.write(f'{item}\n')` 来说稍微简单一些 (3认同)

Sin*_*ion 347

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

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)
Run Code Online (Sandbox Code Playgroud)

读回来:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)
Run Code Online (Sandbox Code Playgroud)

  • +1 - 当Python内置了序列化时,为什么要重新发明轮子? (29认同)
  • +1 - outfile类似于:`open("save.p","wb")`infile类似于:`open("save.p","rb")` (20认同)
  • “警告:pickle 模块不安全。仅解封您信任的数据。有可能构建恶意的 pickle 数据,该数据将在解封期间执行任意代码。切勿解封可能来自不受信任的来源或可能已被篡改的数据和。” - 来自答案链接的同一手册页。 (9认同)
  • 问题是列表必须适合内存.如果不是这种情况,那么逐行确实是一种可能的策略(或者采用其他替代方法,如/sf/ask/502614871/) (2认同)

osa*_*ana 260

最好的方法是:

outfile.write("\n".join(itemlist))
Run Code Online (Sandbox Code Playgroud)

  • 没有尾随换行符,与循环相比使用2x空格. (20认同)
  • 缺点:在将任何文件写出之前,这将构建内存中文件的全部内容,因此峰值内存使用率可能很高. (14认同)
  • 当然,首先要考虑的问题是OP是否需要以换行符结束以及空间量是否重要.你知道他们对过早优化的看法. (7认同)
  • 我永远无法让它发挥作用.我收到此错误:"text ='\n'.join(namelist)+'\n'TypeError:sequence item 0:expected string,list found" (3认同)
  • 您必须确保'namelist'中的所有元素都是字符串. (2认同)

orl*_*uke 90

使用Python 3Python 2.6+语法:

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

这与平台无关.它还使用换行符终止最后一行,这是UNIX的最佳实践.

  • @pyd将for循环替换为`file_handler.write(“ \ n” .join(the_list中项目的str(item)))` (3认同)

Jas*_*ker 86

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

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

如果你检查output.txt:

[1,2,3,4]

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

  • simplejson.load(f)回读已写的内容. (8认同)

Rob*_*obM 38

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

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

file.writelines( list( "%s\n" % item for item in list ) )
Run Code Online (Sandbox Code Playgroud)

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

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

file.writelines( "%s\n" % item for item in list )
Run Code Online (Sandbox Code Playgroud)

此生成器将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
Run Code Online (Sandbox Code Playgroud)

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

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

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
Run Code Online (Sandbox Code Playgroud)

(Linux上的Python 2.6.2)


the*_*max 19

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

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )
Run Code Online (Sandbox Code Playgroud)


Com*_*rch 19

因为我很懒....

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())
Run Code Online (Sandbox Code Playgroud)


Ahm*_*lha 18

简单地:

with open("text.txt", 'w') as file:
    file.write('\n'.join(yourList))
Run Code Online (Sandbox Code Playgroud)


Mar*_*n W 14

一般来说

以下是writelines()方法的语法

fileObject.writelines( sequence )
Run Code Online (Sandbox Code Playgroud)

#!/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()
Run Code Online (Sandbox Code Playgroud)

参考

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


小智 13

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

import numpy as np

np.savetxt('list.txt', list, delimiter="\n", fmt="%s")
Run Code Online (Sandbox Code Playgroud)


mta*_*c85 12

file.write('\n'.join(list))
Run Code Online (Sandbox Code Playgroud)

  • 你如何获得`file`变量? (3认同)

sha*_*kar 8

with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")
Run Code Online (Sandbox Code Playgroud)


小智 8

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

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


Nan*_*aju 7

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

f = open("myfile.txt","wb")
print(mylist, file=f)
Run Code Online (Sandbox Code Playgroud)


Pro*_*rox 5

我最近发现 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())
Run Code Online (Sandbox Code Playgroud)