Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将行追加到文件并覆盖-python_Python_Json_Append - Fatal编程技术网

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

将行追加到文件并覆盖-python,python,json,append,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) 但这会附加所有数据,而不仅仅是预期的行。首先,您需要读取JSON文件并在JSON.load()方法中传递第

如何将一行附加到
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)

但这会附加所有数据,而不仅仅是预期的行。首先,您需要读取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)

首先,您需要读取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)

对不起,请看我的编辑。你用
r+
而不是我对
w
的建议是正确的;前者既写又读。我认为
dict
没有
append
方法,因为当我用
数据行运行代码时,append({c':3})
会给我
属性错误:“dict”对象没有属性“append”
对不起,请参阅我的编辑。你用
r+
而不是我对
w
的建议是正确的;前者既写又读。我认为
dict
没有
append
方法,因为当我用
data.append({c':3})行运行代码时,它会给我
AttributeError:'dict'对象没有属性'append'