为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

摇曳的蔷薇 2023-06-06 16:30:10
我遇到了以下问题,下面的代码示例每次调用都会返回太多大括号: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)


查看完整回答
反对 回复 2023-06-06
  • 1 回答
  • 0 关注
  • 159 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号