我遇到了以下问题,下面的代码示例每次调用都会返回太多大括号: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
提交
取消