我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
当前回答
你还可以通过以下步骤:
例子:
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)
其他回答
还有另一种方式。使用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的,它是人类可读的,并且它可以被其他语言的其他程序读取。
在一般情况下
下面是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
将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])
with open ("test.txt","w")as fp:
for line in list12:
fp.write(line+"\n")
设avg为列表,则:
In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
您可以根据自己的需求使用%e或%s。