【问题标题】:Python - How to update a value in a json file?Python - 如何更新 json 文件中的值?
【发布时间】:2020-02-18 05:48:26
【问题描述】:

我讨厌 json 文件。它们笨重且难以处理:(请告诉我为什么以下方法不起作用:

with open('data.json', 'r+') as file_object:
        data = json.load(file_object)[user_1]['balance']
        am_nt = 5
        data += int(am_nt['amount'])
        print(data)
        file_object[user_1]['balance'] = data

通过反复试验(以及许多打印语句),我发现它打开文件,转到正确的位置,然后实际上添加了 am_nt,但我无法更新原始 json 文件。请帮助我 :( :( 。我明白了:

2000
TypeError: '_io.TextIOWrapper' object is not subscriptable

【问题讨论】:

    标签: json python-3.x dictionary


    【解决方案1】:

    json 使用起来很有趣,因为它类似于 python 数据结构。

    错误是:object is not subscriptable 此错误针对此行: file_object[user_1]['balance'] = data

    file_object 不是可以像上面那样更新的 json/字典数据。因此出现错误。

    尝试读取json数据: data=json.load(file_object)

    然后将数据作为 python 字典进行操作。并保存文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2012-12-06
      • 2021-10-04
      • 1970-01-01
      • 2014-08-26
      • 2020-07-11
      • 1970-01-01
      相关资源
      最近更新 更多