Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 将词典保存到文件_Json_Python 2.7_File_Dictionary - Fatal编程技术网

Json 将词典保存到文件

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非常陌生,我正在尝试获取名为
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)