我遇到了以下問題,下面的代碼示例每次調用都會返回太多大括號: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()其中數據 json 具有以下形式{"sim": true, "pip": false}, 并打電話switchState('path','sim')一次,導致{"sim": false, "pip": false}但第二次調用它會導致:{"sim": true, "pip": false}}任何人都知道這是什么原因?提前致謝
1 回答

楊魅力
TA貢獻1811條經驗 獲得超6個贊
首先我建議使用with語句作為上下文管理器比手動關閉更容易并且更建議。其次,發生這種情況的原因是因為第二次文本較短,因此沒有被覆蓋的額外文本。只需覆蓋該文件,因為這似乎是其中唯一的數據。
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)
添加回答
舉報
0/150
提交
取消