js.dump 中生成的额外大括号

我遇到了以下问题,下面的代码示例每次调用都会返回太多大括号:

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

任何人都知道这是什么原因?提前致谢


摇曳的蔷薇
浏览 160回答 1
1回答

杨魅力

首先我建议使用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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python