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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17055117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:18:27  来源:igfitidea点击:

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

pythonjsonappendnewlinedump

提问by Victor S

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. I want each dictionary entry to be on new line. Any advice would be appreciated.

这会将每个字典附加到“data.txt”,但它是内联的。我希望每个字典条目都在新行上。任何意见,将不胜感激。

回答by agf

Your question is a little unclear. If you're generating hostDictin 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 hostDictto be on a new line:

如果您的意思是希望其中的每个变量都hostDict在一个新行上:

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

When the indentkeyword argument is set it automatically adds newlines.

indent关键字参数设置会自动添加换行符。

回答by Sayali Sonawane

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. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

为避免混淆,同时解释问题和答案。我假设发布此问题的用户想要以 JSON 文件格式保存字典类型对象,但是当用户使用 时json.dump,此方法将其所有内容转储在一行中。相反,他想在新行上记录每个字典条目。要实现此用途:

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

Using indent = 2helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

使用indent = 2帮助我将每个字典条目转储到一个新行上。谢谢@agf。重写此答案以避免混淆。