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

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

当前回答

我建议这个解决方案。

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

其他回答

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

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

你为什么不试试

file.write(str(list))

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

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

还有另一种方式。使用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的,它是人类可读的,并且它可以被其他语言的其他程序读取。

我想你在寻找这样的答案。

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()