我在程序中生成了一个丑陋的列表列表, 看起来像这样:
a= [[93.400000000000006, "high"], [98.600000000000009, 99.0, "high"], [121.30000000000001, 124.1000000000000]]
我将其保存到文本文件中,如下所示:
with open('sample.txt','a') as outfile:
json.dump(a,outfile)
outfile.write("\n\n")
当我打开文本文件时,保存的值是一个眼睛。 如何将每个列表保存到新行?
例如,如果我想将每个列表打印到新行,我可以这样做:
for i in range(len(a)):
print a[i]
谢谢
编辑: 产量有待观察:
[93.400000000000006,“high”]
[98.600000000000009,99.0,“high”]
,即每一行。
答案 0 :(得分:4)
我真的没有理由使用json.dumps
。您可以使用普通的for
循环:
a = [
[93.400000000000006, "high"],
[98.600000000000009, 99.0, "high"],
[111.60000000000001, 112.5, "high"]
]
with open('sample.txt', 'a') as outfile:
for sublist in a:
outfile.write('{}\n'.format(sublist))
以上代码生成输出:
[93.400000000000006, 'high']
[98.600000000000009, 99.0, 'high']
[111.60000000000001, 112.5, 'high']
答案 1 :(得分:1)
您可以尝试:
with open('sample.txt','a') as outfile:
for item in a:
json.dump(item,outfile)
outfile.write("\n\n")
答案 2 :(得分:0)
这应该适合你:
file=open('sample.txt','w')
for i in a:
file.write(str(a))
file.write("\n\n")