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

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

当前回答

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

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

其他回答

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

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

你还可以通过以下步骤:

例子:

my_list=[1,2,3,4,5,"abc","def"]
with open('your_file.txt', 'w') as file:
    for item in my_list:
        file.write("%s\n" % item)

输出:

在your_file.txt中,项目的保存方式如下:

1

2

3

4

5

abc

def

您的脚本也按上述方式保存。

否则,你可以用泡菜

import pickle
my_list=[1,2,3,4,5,"abc","def"]
#to write
with open('your_file.txt', 'wb') as file:
    pickle.dump(my_list, file)
#to read
with open ('your_file.txt', 'rb') as file:
    Outlist = pickle.load(file)
print(Outlist)

输出: [1,2,3,4,5, 'abc', 'def']

它保存转储列表,就像一个列表,当我们加载它时,我们能够读取。

同样由simplejson可能输出与上面相同的结果

import simplejson as sj
my_list=[1,2,3,4,5,"abc","def"]
#To write
with open('your_file.txt', 'w') as file:
    sj.dump(my_list, file)

#To save
with open('your_file.txt', 'r') as file:
    mlist=sj.load(file)
print(mlist)

我建议这个解决方案。

with open('your_file.txt', 'w') as f:        
    list(map(lambda item : f.write("%s\n" % item),my_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 

使用循环:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write(f"{line}\n")

对于Python <3.6:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write("%s\n" % line)

对于Python 2,还可以使用:

with open('your_file.txt', 'w') as f:
    for line in lines:
        print >> f, line

如果您热衷于单个函数调用,至少要删除方括号[],以便每次生成一个要打印的字符串(genexp而不是listcomp)——没有理由占用物化整个字符串列表所需的所有内存。