将行追加到文件并覆盖-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'