Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.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
使用Python在JSON文件中存储项_Python_Json_Dictionary - Fatal编程技术网

使用Python在JSON文件中存储项

使用Python在JSON文件中存储项,python,json,dictionary,Python,Json,Dictionary,我有一个名为test.JSON的JSON文件 {"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"]} 我想向JSON文件中的字典添加新值 import json data = json.load(open("test.json"

我有一个名为test.JSON的JSON文件

{"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"]}

我想向JSON文件中的字典添加新值

import json
data = json.load(open("test.json","r+"))
data["d"] = [str("fourth letter")]
print(data)
上面的代码将以下结果打印到终端

{"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"],"d":["fourth letter"]}
但是我的JSON文件保持不变

{"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"]}
我希望新值像这样存储在JSON文件中

{"a": ["First letter of alphabet"],"b":["Second letter of alphabet"], "c":["Third letter"],"d":["fourth letter"]}

您将在变量上添加列,但要在json上保存新信息,您必须覆盖json文件或创建一个新文件

例如:

import json
data = json.load(open("test.json","r+"))
data["d"] = [str("fourth letter")]

with open("test.json", "w") as jsonFile:
# for creating a new file, just rename the test.json to another name
    json.dump(data, jsonFile)
或者,如此处所述:,您可以使用seek()将光标移回文件开头,然后开始写入,然后使用truncate()处理新数据小于前一个数据的情况。”


您将在变量上添加列,但要在json上保存新信息,您必须覆盖json文件或创建一个新文件

例如:

import json
data = json.load(open("test.json","r+"))
data["d"] = [str("fourth letter")]

with open("test.json", "w") as jsonFile:
# for creating a new file, just rename the test.json to another name
    json.dump(data, jsonFile)
或者,如此处所述:,您可以使用seek()将光标移回文件开头,然后开始写入,然后使用truncate()处理新数据小于前一个数据的情况。”


我无法重现结果。使用您的代码,我得到了您的预期输出。我无法重现结果。使用您的代码,我得到了您的预期输出。非常感谢。。它工作得很好非常感谢你。。它工作得很好