如何将列表中的每个元素保存到.txt文件中,每行一个?

2024-04-20 00:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,pList。我想把它保存到一个文本(.txt)文件中,这样列表中的每个元素都保存在文件的新行中。我该怎么做?

这就是我所拥有的:

def save():
    import pickle
    pList = pickle.load(open('primes.pkl', 'rb'))
    with open('primes.txt', 'wt') as output:
      output.write(str(pList))
    print "File saved."

但是,列表只保存在文件的一行中。 我想要它,所以每个数字(它只包含整数)都保存在一个新的行上。

示例:

pList=[5, 9, 2, -1, 0]
#Code to save it to file, each object on a new line

期望输出:

5
9
2
-1
0

我该怎么做?


Tags: 文件to文本importtxt元素列表output
3条回答

您可以在这里将mapstr一起使用:

pList = [5, 9, 2, -1, 0]
with open("data.txt", 'w') as f:
    f.write("\n".join(map(str, pList)))

请参阅此答案以获取一个函数,该函数将项添加到给定文件的新行中

https://stackoverflow.com/a/13203890/325499

def addToFile(file, what):
    f = open(file, 'a').write(what+"\n") 

所以对于您的问题,您需要遍历列表,而不是将列表传递给文件。

for item in pList:
    addToFile(item)

只需打开文件,用所需的分隔符连接列表,然后将其打印出来。

outfile = open("file_path", "w")
print >> outfile, "\n".join(str(i) for i in your_list)
outfile.close()

由于列表包含整数,因此需要进行转换。(谢谢你的通知,Ashwini Chaudhary)。

不需要创建临时列表,因为生成器是由join方法迭代的(再次感谢Ashwini Chaudhary)。

相关问题 更多 >