python - 更新 JSON 文件的键值
问题描述
我有一个 json 文件
{
"id_1" : "",
"id_2": ""
}
我正在尝试使用以下函数更新每个值
async def UpdateID(self):
await self.bot.wait_until_ready()
while not self.bot.is_closed():
id1 = 1
id2 = 2
with open("file.json", "r+") as r:
config_json = json.load(r)
config_json.update({"id_1": "%s" %(id1)})
config_json.update({"id_2": "%s" %(id2)})
json.dump(config_json,r)
await asyncio.sleep(120)
使用 mode r+
,它复制文件并将其添加到末尾,从而复制所有数据而不是替换。如果我使用r
,我不能写。
如果我使用w
or a
,我会在步骤中收到UnsupportedOperation
,not readable
错误。json.load
使用w
也会使文件为空。
a+ and w+,
在步骤上给出一个JSONDecodeError
,Expecting value: line 1 column 1 (char 0)
错误。json.load
我使用了错误的模式,还是解决原始问题的方法不正确?
解决方案
你可以这样做
import json
async def updateId(self):
do_something()
with open(file_name) as f:
config = json.load(f)
update_your_config()
with open(file_name, 'w') as f:
json.dumps(config, f)
do_something()
推荐阅读
- c++ - OpenCV:加载缓慢
- c# - Richtextbox 拖放不同于表单拖放
- c# - 如何防止对象传递到另一种形式?
- c++ - 如何通过将签名作为模板参数来解析重载函数?
- windows - 如何在 Windows 中将 PostgreSQL ('psql.exe') 添加到 PATH?
- c# - 如何让WebClient在C#中逐行读取
- angular - 在 *ngFor 循环中引用子集合/文档
- java - sun.awt.X11FontManager: java.lang.reflect.InvocationTargetException (Arch Linux)
- javascript - 如何在 css 文件中添加另一个 css 文件?
- c++ - C++ *对角差*问题,我哪里错了?