如何在python中写入json文件?[duplicate]

wwwo4jvm  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(145)

此问题在此处已有答案

How do I write JSON data to a file?(16个答案)
昨天关门了。
我有一个包含数据的json文件

{
  "Theme": "dark_background"
}

我正在使用下面的代码读取Theme的值

import json
    with open("setting.json", "r") as f:
        stuff = json.load(f)
        f.close()
    style = stuff['Theme']

现在我想写/改变主题的值,怎么做?

s8vozzvw

s8vozzvw1#

使用json.dump()或 * json.dumps()* 函数将对象(列表、字典等)序列化为JSON格式。

import json
with open("setting.json", "r") as f:
    stuff = json.load(f)
style = stuff['Theme']
print("old:", style)

# set new value in dictionary
stuff["Theme"] = "light_background"
print("new:", stuff['Theme'])

# write JSON output to file
with open("setting.json", "w") as fout:
    json.dump(stuff, fout)

输出:

old: dark_background
new: light_background

要使JSON输出更美观,请使用 indent 参数。

with open("setting.json", "w") as fout:
    json.dump(stuff, fout, indent=4)

相关问题