我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:
f.writelines([f"{line}\n" for line in lines])
当前回答
我想你在寻找这样的答案。
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()
其他回答
因为我很懒....
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())
你为什么不试试
file.write(str(list))
设avg为列表,则:
In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
您可以根据自己的需求使用%e或%s。
使用numpy。Savetxt也是一个选项:
import numpy as np
np.savetxt('list.txt', list, delimiter="\n", fmt="%s")
还有另一种方式。使用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的,它是人类可读的,并且它可以被其他语言的其他程序读取。