8

我有一个清单,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

我该怎么做呢?

4

3 回答 3

11

只需打开您的文件,使用所需的分隔符加入您的列表,然后打印出来。

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

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

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

于 2012-11-17T19:39:22.320 回答
11

你可以mapstr这里使用:

pList = [5, 9, 2, -1, 0]
with open("data.txt", 'w') as f:
    f.write("\n".join(map(str, pList)))
于 2012-11-17T19:46:59.573 回答
0

请参阅此答案以获取将项目添加到给定文件的新行的函数

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

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

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

for item in pList:
    addToFile(item)
于 2012-11-17T19:45:40.313 回答