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

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

当前回答

序列化列表到文本文件与逗号分隔值

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

其他回答

我建议这个解决方案。

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

设avg为列表,则:

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

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

在Python 3中,你可以使用print和*进行参数解包:

with open("fout.txt", "w") as fout:
    print(*my_list, sep="\n", file=fout)

这个逻辑首先将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 
with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")