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

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

当前回答

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

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

其他回答

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

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

你打算怎么处理这个文件?这个文件是否存在于人类,或其他具有明确互操作性要求的程序?

如果您只是试图将列表序列化到磁盘,以便稍后由同一python应用程序使用,则应该pickle该列表。

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

再读一遍:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

更简单的是:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

要确保项目列表中的所有项目都是字符串,请使用生成器表达式:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

记住,项目列表占用内存,所以要注意内存消耗。

因为我很懒....

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

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

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