我是Python的新手,我正在尝试将我的字典内容称为python_diction
(位于更大的文件中)并将该数据保存到一个名为python_diction_saved.json
的新文件中。我觉得我非常接近我目前收到的错误python_diction_saved.json
未定义。
非常感谢任何帮助。
import json
f = open("python_diction.txt","w")
python_diction = {}
python_diction["items"] = []
python_diction["items"].append({"hello":1,"hi":2})
python_diction["items"].append({"hello":42,"hi":65})
python_diction["numbers"] = [1,2,3,5,7,8]
f.write(json.dumps(python_diction_saved.json))
f.close()
答案 0 :(得分:1)
为了将python_diction
写入名为python_diction_saved.json
的文件,您可以使用json.dump
(以避免必须自己编写):
import json
python_diction = {}
python_diction["items"] = []
python_diction["items"].append({"hello":1,"hi":2})
python_diction["items"].append({"hello":42,"hi":65})
python_diction["numbers"] = [1,2,3,5,7,8]
with open("python_diction_saved.json") as output_file:
json.dump(python_diction, output_file)