我如何写一个列表文件?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

其他回答

file.write('\n'.join(list))

你还可以通过以下步骤:

例子:

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:
    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)——没有理由占用物化整个字符串列表所需的所有内存。

因为我很懒....

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

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

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

import pickle

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

再读一遍:

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