我正在尝试将字典添加到已有2个字典的json文件中。但这给了我初始文件和结果,它们都放在同一个json文件中。我的代码如下。预先感谢大家。
import json
import os
cwd = os.getcwd()
fp = cwd + '/xero_credentials.json'
def json_append():
data_object = {
"clientName": "Company Test",
"clientId": "null",
"clientSecret": "null",
"redirect_url": "http://localhost:8080/callback",
'scopes': "offline_access accounting.transactions.read accounting.journals.read",
'refreshToken': "null"
}
with open(fp, 'r+') as json_file:
data = json.load(json_file)
data_dictionary = data['credentials']
data_dictionary.append(data_object)
json.dump(data, json_file, indent = 4, sort_keys=True)
json_file.close()
# **********
json_append()
这是结果:
{
"credentials": [
{
"clientName": "C1",
"clientId": "null"
},
{
"clientName": "C2",
"clientId": "null"
}
]
}
{
"credentials": [
{
"clientName": "C1",
"clientId": "null"
},
{
"clientName": "C2",
"clientId": "null"
},
{
"clientName": "C3",
"clientId": "null"
}
]
}
答案 0 :(得分:1)
很难就地更新文件(某些特殊情况除外),因此通常通常必须先将其全部内容读取到内存中,然后进行更新,然后使用它重写整个文件。
>这是我的意思:
import json
import os
cwd = os.getcwd()
fp = cwd + '/xero_credentials.json'
def json_append():
data_object = {
"clientName": "Company Test",
"clientId": "null",
"clientSecret": "null",
"redirect_url": "http://localhost:8080/callback",
'scopes': "offline_access accounting.transactions.read accounting.journals.read",
'refreshToken': "null"
}
# Read the entire file.
with open(fp, 'r') as json_file:
data = json.load(json_file)
# Update the data read.
credentials = data['credentials']
credentials.append(data_object)
# Update the file by rewriting it.
with open(fp, 'w') as json_file:
json.dump(data, json_file, indent=4, sort_keys=True)
json_append()
更新的文件:
{
"credentials": [
{
"clientId": "null",
"clientName": "C1"
},
{
"clientId": "null",
"clientName": "C2"
},
{
"clientId": "null",
"clientName": "Company Test",
"clientSecret": "null",
"redirect_url": "http://localhost:8080/callback",
"refreshToken": "null",
"scopes": "offline_access accounting.transactions.read accounting.journals.read"
}
]
}
答案 1 :(得分:0)
编辑:误解了这个问题。
问题是打开文件时正在使用“ r +”模式。这意味着您将能够读取和追加但不能编辑,这就是您要尝试做的。
只需使用with open(fp, 'w')
。
此外,您无需显式关闭文件。一旦离开范围,诸如with
之类的上下文管理器就会自动执行此操作。