Vic*_*r S 52 python json newline dump append
我的代码创建了一个字典,然后存储在一个变量中.我想将每个字典写入JSON文件,但我希望每个字典都在一个新行上.
我的字典:
hostDict = {"key1": "val1", "key2": "val2", "key3": {"sub_key1": "sub_val2", "sub_key2": "sub_val2", "sub_key3": "sub_val3"}, "key4": "val4"}
Run Code Online (Sandbox Code Playgroud)
我的部分代码:
g = open('data.txt', 'a')
with g as outfile:
json.dump(hostDict, outfile)
Run Code Online (Sandbox Code Playgroud)
这会将每个字典附加到'data.txt',但它会内联.我希望每个字典条目都在新行上.任何意见,将不胜感激.
agf*_*agf 95
你的问题有点不清楚.如果你hostDict在循环中生成:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('\n')
Run Code Online (Sandbox Code Playgroud)
如果您的意思是希望每个变量都hostDict在一个新行上:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
Run Code Online (Sandbox Code Playgroud)
当indent关键字参数设置会自动添加换行符.
Say*_*ane 10
为避免混淆,同时解释问题和答案。我假设发布此问题的用户想要以 JSON 文件格式保存字典类型对象,但是当用户使用 时json.dump,此方法将其所有内容转储在一行中。相反,他想在新行上记录每个字典条目。要实现此用途:
with g as outfile:
json.dump(hostDict, outfile,indent=2)
Run Code Online (Sandbox Code Playgroud)
使用indent = 2帮助我将每个字典条目转储到一个新行上。谢谢@agf。重写此答案以避免混淆。