将行追加到文件并覆盖-python

时间:2020-01-11 03:28:54

标签: python json append

如何在json文件中附加一行并用相同的名称覆盖?

data.json    
{
 'a': 1,
 'b': 2}

我尝试过

with open('data.json', 'r+') as json_file:
    data = json.load(json_file)
    data.update({'c': 3})
    json.dump(data,json_file)

但这会附加所有数据,而不仅仅是预期的行

1 个答案:

答案 0 :(得分:2)

首先,您需要阅读JSON文件并在json.load()方法中传递第二个参数,该参数将保留字典的顺序。因此,当将键值对分配给字典时,OrderedDict会自动将其附加到末尾。最后,写入文件。

import json
from collections import OrderedDict

with open('data.json', 'r') as json_file:
    data = json.load(json_file, object_pairs_hook=OrderedDict)
    data['c'] = 3

with open('data.json', 'w') as json_file:
    json.dump(data, json_file)
相关问题