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

Rus*_*hal 3 python io text list

我有一个清单,pList.我想将其保存到text(.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."
Run Code Online (Sandbox Code Playgroud)

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

例:

pList=[5, 9, 2, -1, 0]
#Code to save it to file, each object on a new line
Run Code Online (Sandbox Code Playgroud)

期望的输出:

5
9
2
-1
0
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Rub*_*ens 7

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

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

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

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

  • 为什么当 `outfile.write` 可以在 py2k 和 py3k 上工作时使用 `print >>`? (3认同)

Ash*_*ary 6

你可以mapstr这里使用:

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