我如何写一个列表文件?writelines()不插入换行符,所以我需要这样做:

f.writelines([f"{line}\n" for line in lines])

当前回答

设avg为列表,则:

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

您可以根据自己的需求使用%e或%s。

其他回答

在Python3中你可以使用这个循环

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

如果在python3上,还可以使用print函数,如下所示。

f = open("myfile.txt","wb")
print(mylist, file=f)

我建议这个解决方案。

with open('your_file.txt', 'w') as f:        
    list(map(lambda item : f.write("%s\n" % item),my_list))   
file.write('\n'.join(list))

这个逻辑首先将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