我正在使用Discord.py编写一个Discord bot,我想运行一些命令,并将数据写入json文件。现在,当我运行其中一个命令时,它只是覆盖了整个json文件
@bot.command()
async def setstatus(ctx, arg):
await ctx.send('The server status channel has been set to ' + arg)
newArg = ""
for character in arg:
if character.isalnum():
newArg += character
data['statusChannel'] = newArg
writeToJSON(path, fileName, data)
这是writeToJSON函数
def writeToJSON(path, fileName, data):
filePathNameWExt = './' + path + '/' + fileName + '.json'
with open(filePathNameWExt, 'w') as fp:
json.dump(data, fp)
这就是JSON文件不好的原因之一,您无法覆盖单个值,它将始终覆盖整个文件。如果多个命令同时运行,则可能会出现竞争条件,如果不想切换到关系数据库,则可以使用类似
asyncio.Lock
的命令如果要向文件中添加文本,则需要在
open
函数中使用'a'
参数,而不是'w'
,这将覆盖整个文件因为不能向json添加数据,所以我认为最好使用pickle
可以使用pickle将对象读写到文件中。使用pickle,您可以读取并向文件中添加更多数据。如果您的数据是一个列表,您可以这样做:
相关问题 更多 >
编程相关推荐