将列表保存到.txt文件中,每个值之间都有行

时间:2018-10-27 10:59:34

标签: python python-3.x

所以我找到了这个答案(stackoverflow.com/questions/33686747/save-a-list-to-a-txt-file),这很好,但没有告诉我如何将值放在单独的行上在创建的文本文件中。

这是我的代码,如果有帮助的话:

  

heightandweight = ['James',73,1.82,'Peter',78,1.80,'Beth',65,1.53,'Mags',66,1.50,'Joy',62,1.34]

     

使用open(“ heightandweight.txt”,“ w”)作为输出:

     
    

output.write(str(heightandweight))

  

1 个答案:

答案 0 :(得分:1)

您需要遍历列表,逐行添加每行,并添加“ \ n”以表示您想要换行:

with open("heightandweight.txt", "w") as output:
    for i in heightandweight:
        output.write(str(i) + "\n")

给予

James
73
1.82
Peter
78
1.8
Beth
65
1.53
Mags
66
1.5
Joy
62
1.34

如果您想在同一行上添加名称及其高度和重量,则情况会有些复杂:

with open("heightandweight.txt", "w") as output:
    for i, name in enumerate(heightandweight, 0):
        if i % 3 == 0:
            output.write("%s %i %.2f\n" % (heightandweight[i], heightandweight[i+1], heightandweight[i+2]))

这使用enumerate获得一个整数值i,每次for循环迭代时,该整数值都会增加1。然后,检查它是否为三的倍数,如果是,则使用string formatting将其写入文件。输出如下:

James 73 1.82
Peter 78 1.80
Beth 65 1.53
Mags 66 1.50
Joy 62 1.34

这实际上并不是最好的方法。最好使用列表列表:[['James', 73, 1.82], ['Peter', 78, 1.80], ['Beth', 65, 1.53], ['Mags', 66, 1.50], ['Joy', 62, 1.34]]