Python JSON 转储/附加到 .txt,每个变量都在新行上 [英] Python JSON dump / append to .txt with each variable on new line

查看:29
本文介绍了Python JSON 转储/附加到 .txt,每个变量都在新行上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码创建了一个字典,然后将其存储在一个变量中.我想将每个字典写入一个 JSON 文件,但我希望每个字典都在一个新行上.

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.

我的字典:

hostDict = {"key1": "val1", "key2": "val2", "key3": {"sub_key1": "sub_val2", "sub_key2": "sub_val2", "sub_key3": "sub_val3"}, "key4": "val4"}

我的部分代码:

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

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

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.

推荐答案

你的问题有点不清楚.如果您在循环中生成 hostDict:

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('\n')

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

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)

当设置 indent 关键字参数时,它会自动添加换行符.

When the indent keyword argument is set it automatically adds newlines.

这篇关于Python JSON 转储/附加到 .txt,每个变量都在新行上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆