所以我找到了这个答案(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))
您需要遍历列表,分别添加每一行,添加“\n”以表示您需要新行:
给予
如果你想在同一行上加上一个名字和他们的身高和体重,那么事情就要复杂一些:
它使用
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]]
相关问题 更多 >
编程相关推荐