首页 » 编程设计

python之如何在将数据转储到其中之前清空json文件

2025年04月02日9daizhj

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"}]} 

所以我写了这段代码:

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": [{"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 中,然后关闭该文件。 做任何你需要的操作 再次打开文件,这次是为了写入。转储数据,关闭文件。


阅读延展