我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
更简单的是:
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))
记住,项目列表占用内存,所以要注意内存消耗。
使用循环:
with open('your_file.txt', 'w') as f:
for line in lines:
f.write(f"{line}\n")
对于Python <3.6:
with open('your_file.txt', 'w') as f:
for line in lines:
f.write("%s\n" % line)
对于Python 2,还可以使用:
with open('your_file.txt', 'w') as f:
for line in lines:
print >> f, line
如果您热衷于单个函数调用,至少要删除方括号[],以便每次生成一个要打印的字符串(genexp而不是listcomp)——没有理由占用物化整个字符串列表所需的所有内存。
你打算怎么处理这个文件?这个文件是否存在于人类,或其他具有明确互操作性要求的程序?
如果您只是试图将列表序列化到磁盘,以便稍后由同一python应用程序使用,则应该pickle该列表。
import pickle
with open('outfile', 'wb') as fp:
pickle.dump(itemlist, fp)
再读一遍:
with open ('outfile', 'rb') as fp:
itemlist = pickle.load(fp)
还有另一种方式。使用simplejson序列化为json(在python 2.6中包含为json):
>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()
如果你检查output.txt:
[1, 2, 3, 4]
这很有用,因为它的语法是python的,它是人类可读的,并且它可以被其他语言的其他程序读取。
我认为探索使用genexp的好处会很有趣,所以下面是我的看法。
问题中的例子使用方括号来创建一个临时列表,因此相当于:
file.writelines( list( "%s\n" % item for item in list ) )
这将不必要地构造一个包含所有将被写入的行的临时列表,这可能会消耗大量的内存,这取决于列表的大小以及str(item)的输出有多详细。
去掉方括号(相当于去掉上面的包装列表()调用)将会传递一个临时生成器给file.writelines():
file.writelines( "%s\n" % item for item in list )
该生成器将按需创建以换行符结束的项目对象表示(即当它们被写入时)。这很好,有几个原因:
内存开销很小,即使对于非常大的列表也是如此 如果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
(我通过限制Python的max触发了此错误。使用ulimit -v 102400虚拟内存到~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
(Python 2.6.2 on Linux)
设avg为列表,则:
In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
您可以根据自己的需求使用%e或%s。
使用Python 3和Python 2.6+语法:
with open(filepath, 'w') as file_handler:
for item in the_list:
file_handler.write("{}\n".format(item))
这是平台独立的。它还使用换行符结束最后一行,这是UNIX的最佳实践。
从Python 3.6开始,"{}\n".format(item)可以用f-string替换:f"{item}\n"。
在一般情况下
下面是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
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
How It Works: First, open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. The mode can be a read mode (’r’), write mode (’w’) or append mode (’a’). We can also specify whether we are reading, writing, or appending in text mode (’t’) or binary mode (’b’). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the file to be a ’t’ext file and opens it in ’r’ead mode. In our example, we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file.
上面的例子来自Swaroop C H编写的《A Byte of Python》一书。 swaroopch.com
如果在python3上,还可以使用print函数,如下所示。
f = open("myfile.txt","wb")
print(mylist, file=f)
序列化列表到文本文件与逗号分隔值
mylist = dir()
with open('filename.txt','w') as f:
f.write( ','.join( mylist ) )
因为我很懒....
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())
这个逻辑首先将list中的项转换为字符串(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
在Python3中你可以使用这个循环
with open('your_file.txt', 'w') as f:
for item in list:
f.print("", item)
在Python 3中,你可以使用print和*进行参数解包:
with open("fout.txt", "w") as fout:
print(*my_list, sep="\n", file=fout)
使用numpy。Savetxt也是一个选项:
import numpy as np
np.savetxt('list.txt', list, delimiter="\n", fmt="%s")
将stdout重定向到一个文件也可以用于此目的:
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])
你还可以通过以下步骤:
例子:
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
您的脚本也按上述方式保存。
否则,你可以用泡菜
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)
我建议这个解决方案。
with open('your_file.txt', 'w') as f:
list(map(lambda item : f.write("%s\n" % item),my_list))
我最近发现Path很有用。帮助我绕过不得不打开('file')作为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())
我想你在寻找这样的答案。
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()