我正在嘗試使用 Discord 機器人創建一個功能,它可以計算已運行的命令數量,并將其存盤在名為 .json 的 JSON 檔案data.json中。這是代碼:
import json
# Read 'data.json'
with open("data.json", "r") as d:
datar = json.load(d)
com = datar.get("commands-run")
# Functions
def command_increase():
commands_run = com 1
dataw = open("data.json", "w")
dataw["commands-run"] = commands_run
這是 JSON 檔案:
{
"commands-run": 0
}
這是我在運行命令并嘗試增加 JSON 檔案中的值時遇到的錯誤:
TypeError: '_io.TextIOWrapper' object does not support item assignment
最重要的是,它還完全擦除了 JSON 檔案。我的意思是,它只是清除了所有內容。甚至括號。
uj5u.com熱心網友回復:
當您執行 ajson.load時,它會將您的 json 資料加載到 dict 中。您可以在此 dict 中增加命令計數器,并在其末尾將 dict 重新寫入您的 json 檔案。
import json
# Read 'data.json'
with open("data.json", "r") as d:
datar = json.load(d)
com = datar.get("commands-run")
# Functions
def command_increase():
commands_run = com 1
datar["commands-run"] = commands_run
with open("data.json", "w") as dataw:
dataw.write(json.dumps(datar, indent=4))
command_increase()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483021.html
下一篇:陣列中的最小絕對差
