简体   繁体   English

Python JSON 转储/附加到 .txt,每个变量都在新行上

[英]Python JSON dump / append to .txt with each variable on new line

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.我想将每个字典写入一个 JSON 文件,但我希望每个字典都在一个新行上。

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.这会将每个字典附加到“data.txt”,但它是内联的。 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:如果您在循环中生成hostDict

with open('data.txt', 'a') as outfile:
    for hostDict in ....:
        json.dump(hostDict, outfile)
        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:如果您的意思是希望hostDict每个变量都在一个新行上:

with open('data.txt', 'a') as outfile:
    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.设置indent关键字参数后,它会自动添加换行符。

To avoid confusion, paraphrasing both question and answer.为避免混淆,同时解释问题和答案。 I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump , this method dumped all its content in one line.我假设发布此问题的用户想要以 JSON 文件格式保存字典类型对象,但是当用户使用json.dump ,此方法将其所有内容转储在一行中。 Instead, he wanted to record each dictionary entry on a new line.相反,他想在新行上记录每个字典条目。 To achieve this use:要实现此用途:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line.使用indent = 2帮助我将每个字典条目转储到新行。 Thank you @agf.谢谢@agf。 Rewriting this answer to avoid confusion.重写此答案以避免混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM