Json 将词典保存到文件
我对Python非常陌生,我正在尝试获取名为Json 将词典保存到文件,json,python-2.7,file,dictionary,Json,Python 2.7,File,Dictionary,我对Python非常陌生,我正在尝试获取名为Python\u diction(位于一个较大的文件中)的字典内容,并将该数据保存到一个名为Python\u diction\u saved.json的新文件中。我觉得我很接近我目前收到的错误是python\u diction\u saved。json没有定义 任何帮助都将不胜感激 import json f = open("python_diction.txt","w") python_diction = {} python_diction["ite
Python\u diction
(位于一个较大的文件中)的字典内容,并将该数据保存到一个名为Python\u diction\u saved.json的新文件中。我觉得我很接近我目前收到的错误是python\u diction\u 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()
为了将python\u diction
写入名为python\u diction\u saved.json
的文件,您可以使用json.dump
(避免自己编写):
python_diction_saved
=>python_diction
很好,解决了第一个回溯错误,但现在我又遇到了一个回溯错误……f.write(json.dumps(python_diction_saved.json))AttributeError:“dict”对象没有属性“json”来吧:python\u diction\u saved.json
=>python\u diction
您还需要打开另一个名为“python\u diction\u saved.json”
@Faibbus否的文件,该文件已经在“python\u diction.txt”下打开。
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)