我遇到了以下問題,下面的代碼示例每次調(diào)用都會返回太多大括號:import json as js
def switchState(path, type):
file = open(path + '/states.txt', 'r+')
json = js.loads(file.read())
json[type] = not json[type]
file.seek(0)
js.dump(json, file)
file.close()其中數(shù)據(jù) json 具有以下形式{"sim": true, "pip": false}, 并打電話switchState('path','sim')一次,導(dǎo)致{"sim": false, "pip": false}但第二次調(diào)用它會導(dǎo)致:{"sim": true, "pip": false}}任何人都知道這是什么原因?提前致謝
1 回答

楊魅力
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
首先我建議使用with語句作為上下文管理器比手動(dòng)關(guān)閉更容易并且更建議。其次,發(fā)生這種情況的原因是因?yàn)榈诙挝谋据^短,因此沒有被覆蓋的額外文本。只需覆蓋該文件,因?yàn)檫@似乎是其中唯一的數(shù)據(jù)。
def switchState(path, type):
with open(path + '/states.txt') as infile:
json = js.load(file)
json[type] = not json[type]
with open(path + '/states.txt', 'w') as infile:
js.dump(json, file)
添加回答
舉報(bào)
0/150
提交
取消