【问题标题】:Extra curly bracket generated in js.dump在 js.dump 中生成额外的大括号
【发布时间】:2020-08-18 17:40:54
【问题描述】:

我遇到了以下问题,下面的代码示例每秒返回一个大括号太多:

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()

in 而数据 json 的格式为

{"sim": true, "pip": false}

,并调用

switchState('path','sim')

一次,导致

{"sim": false, "pip": false}

但第二次调用它会导致:

{"sim": true, "pip": false}}

有人知道这是什么原因吗? 提前致谢

【问题讨论】:

标签: python json file-handling


【解决方案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)
    

【讨论】:

  • 或者写完后拨打file.truncate()
  • 不敢相信我监督了这样的错误,你的两个答案都有效,谢谢!
  • @Barmar 没想到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 2012-02-20
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多