本文介绍了Python JSON转储/附加到.txt,每个变量都在新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
My code creates a dictionary, which is then stored in a variable. I want to write each dictionary to a JSON file, but I want each dictionary to be on a new line.
My dictionary:
hostDict = {"key1": "val1", "key2": "val2", "key3": {"sub_key1": "sub_val2", "sub_key2": "sub_val2", "sub_key3": "sub_val3"}, "key4": "val4"}
Part of my code:
g = open('data.txt', 'a')
with g as outfile:
json.dump(hostDict, outfile)
This appends each dictionary to 'data.txt' but it does so inline. I want each dictionary entry to be on new line. Any advice would be appreciated.
解决方案
Your question is a little unclear. If you're generating hostDict
in a loop:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('
')
If you mean you want each variable within hostDict
to be on a new line:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
When the indent
keyword argument is set it automatically adds newlines.
这篇关于Python JSON转储/附加到.txt,每个变量都在新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!