在python dict中添加key的新值。另一个文件中的jsom

时间:2017-06-20 06:43:30

标签: python dictionary

美好的一天!我对python字典和json有疑问!在一个文件中我创建了具有以下结构的json字典:

{"face_1": {"face_rect": "(127, 68, 177, 177)", "Age": 1, "Gender": 1}}

因为它使用这个代码(i - 面的数量,(x,y,w,h) - 坐标的矩形。):

for i, (x, y, w, h) in enumerate(faces):
        face = dict()
        face["face_{}".format(i + 1)] =  {"face_rect": str((x, y, w, h)), "Age": 1, "Gender": 1}
        with open('face.json', 'a') as fp:
            data_to_write = json.dumps(face)
            fp.write(data_to_write + '\n')

在此之前,一切都很棒。我的问题 - 如何在另一个py文件和CHANGE值'Age','Gender'打开这个字典(face.json)并保存它? 感谢您的时间!

1 个答案:

答案 0 :(得分:1)

您可以使用json.load加载字典:

OFFSET

然后,您可以使用json.dump

再次保存数据
with open('face.json') as fp:
    data = json.load(fp)

# Make some modifications here.

请注意,无需手动调用with open('face.json', 'w') as fp: json.dump(data, fp) ,因为fp.write已经为您处理了此问题。此外,在打开文件时,您要使用模式json.dump而不是'w',否则您不会覆盖旧数据,而只是将新字典附加到最后。这也将使json格式无效。