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

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

当前回答

在一般情况下

下面是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

其他回答

使用numpy。Savetxt也是一个选项:

import numpy as np

np.savetxt('list.txt', list, delimiter="\n", fmt="%s")

将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")

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

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

简单:

with open("text.txt", 'w') as file:
    file.write('\n'.join(yourList))