Python JSON dump / append to .txt with each variable on new line
我的代码创建一个字典,然后将其存储在一个变量中。我想把每本字典都写进一个JSON文件,但我想把每本字典都写在一个新行上。
我的字典:
1 | hostDict = {"key1":"val1","key2":"val2","key3": {"sub_key1":"sub_val2","sub_key2":"sub_val2","sub_key3":"sub_val3"},"key4":"val4"} |
我的部分代码:
1 2 3 | g = open('data.txt', 'a') with g as outfile: json.dump(hostDict, outfile) |
这会将每个字典附加到'data.txt'中,但它是内联的。我希望每个词典条目都在新行。任何建议都将不胜感激。
你的问题有点不清楚。如果在循环中生成
1 2 3 4 5 | with open('data.txt', 'a') as outfile: for hostDict in ....: json.dump(hostDict, outfile) outfile.write(' ') |
如果您的意思是希望
1 2 | with open('data.txt', 'a') as outfile: json.dump(hostDict, outfile, indent=2) |
当设置