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

2024-10-04 07:25:10 发布

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

所以我找到了这个答案(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]

with open("heightandweight.txt", "w") as output:

output.write(str(heightandweight))


Tags: to答案代码txtcomoutputsavestackoverflow
1条回答
网友
1楼 · 发布于 2024-10-04 07:25:10

您需要遍历列表,分别添加每一行,添加“\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循环迭代时,这个整数值就会递增一。然后检查它是三的倍数,如果是,则使用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]]

相关问题 更多 >