如何在Python中将内容写入JSON文件?
如何在Python中将内容写入JSON文件?
这个问题已经有了答案:
我有一份包含数据的 JSON 文件
{ "Theme": "dark_background" }
我使用以下代码来读取“主题”属性的值
import json with open("setting.json", "r") as f: stuff = json.load(f) f.close() style = stuff['Theme']
现在我想要写入/更改“主题”属性的值,该怎么做?
admin 更改状态以发布 2023年5月23日
使用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输出,请使用缩进参数。
with open("setting.json", "w") as fout: json.dump(stuff, fout, indent=4)