Python 如何在将数据转储到json文件之前清空该文件

Python 如何在将数据转储到json文件之前清空该文件,python,json,Python,Json,python 3.5 嗨,我有以下代码向json数据添加元素: jsonFile = open("json.json", mode="r+", encoding='utf-8') jdata = json.load(jsonFile) jdata['chat_text'].insert(0, {'x':'x'}) json.dump(jdata, jsonFile) jsonFile.close() 但结果是: 第一个数据 {"chat_text": [{"a": "b", "c": "d",

python 3.5

嗨,我有以下代码向json数据添加元素:

jsonFile = open("json.json", mode="r+", encoding='utf-8')
jdata = json.load(jsonFile)
jdata['chat_text'].insert(0, {'x':'x'})
json.dump(jdata, jsonFile)
jsonFile.close()
但结果是:

第一个数据

{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}{"chat_text": [{'x':'x'},{"a": "b", "c": "d", "e": "f"}]}
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
                                               {"chat_text": [{"x","x"},{"a": "b", "c": "d", "e": "f"}]}
编辑的数据

{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}{"chat_text": [{'x':'x'},{"a": "b", "c": "d", "e": "f"}]}
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
                                               {"chat_text": [{"x","x"},{"a": "b", "c": "d", "e": "f"}]}
所以我写了这段代码:

jsonFile = open("json.json", mode="r+", encoding='utf-8')
jdata = json.load(jsonFile)
jdata['chat_text'].insert(0, {'x':'x'})
open('json.json', mode='w').close() #deleting first data
json.dump(jdata, jsonFile)
jsonFile.close()
结果将是:

第一个数据

{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}{"chat_text": [{'x':'x'},{"a": "b", "c": "d", "e": "f"}]}
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
                                               {"chat_text": [{"x","x"},{"a": "b", "c": "d", "e": "f"}]}
编辑的数据

{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}{"chat_text": [{'x':'x'},{"a": "b", "c": "d", "e": "f"}]}
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
                                               {"chat_text": [{"x","x"},{"a": "b", "c": "d", "e": "f"}]}
正如你们看到的,它用空格替换了第一个数据,我希望它什么都不是


有什么想法吗?

问题在于,您要以不同的模式打开文件两次

jsonFile = open("json.json", mode="r")
jdata = json.load(jsonFile)
jsonFile.close()
jdata['chat_text'].insert(0, {'x':'x'})
jsonFile = open('json.json', mode='w+')
json.dump(jdata, jsonFile)
jsonFile.close()
因此,前3行打开文件并将其加载到jdata中,然后关闭该文件。 做你需要的任何操作
再次打开文件,以便这次写入。转储数据,关闭文件。

为什么要在更新json之前和之后加载json,只需在更新
char\u text之后将json加载到文件中
您编辑的json数据中存在语法错误。无效json为什么在更新json前后加载json,只需在更新后将json加载到文件中
char\u text
open('r')->load->close->open('w')->dump->close.
jsonFile.seek(0);json.dump(jdata,jsonFile)