如何更新写在文件中的字典

时间:2019-06-15 18:30:44

标签: python python-3.x

我试图弄清楚如何用已经写入文件的python更新字典。 例如。 file.txt包含一个字典:

my_car = {"brand":"Ford", "model":"Mustang", "year":1964}

现在,我也想添加“马力”,并将模型更新为“ Shelby Mustang”。

我尝试使用JSON模块,但无法正确找出。

我的方法:

import json
with open('file.txt','r+') as f:
    y = json.load(f)
    y['horsepower'] = '225KW'

未显示任何错误,但我的文件未更新。

1 个答案:

答案 0 :(得分:-1)

您只读取了文件,但没有写新的字典。

import json

with open('file.txt', 'r+') as f_r:
    y = json.load(f_r)
    with open('file.txt', 'w') as f_w:
        f_w.write(y.update({'horsepower': '225KW'})