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) - 没有理由占用所需的所有内存实现整个字符串列表.
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)
osa*_*ana 260
最好的方法是:
outfile.write("\n".join(itemlist))
Run Code Online (Sandbox Code Playgroud)
orl*_*uke 90
使用Python 3和Python 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的最佳实践.
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,它是人类可读的,并且可以被其他语言的其他程序读取.
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)
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)
如果你在python3上,你也可以使用print函数,如下所示.
f = open("myfile.txt","wb")
print(mylist, file=f)
Run Code Online (Sandbox Code Playgroud)
我最近发现 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)
| 归档时间: |
|
| 查看次数: |
1424426 次 |
| 最近记录: |