Python 写入Discord bot的配置文件

Python 写入Discord bot的配置文件,python,discord.py,Python,Discord.py,我正在使用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 ar

我正在使用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)

如果要向文件中添加文本,则需要使用
打开
函数中的
'a'
参数,而不是覆盖整个文件的
'w'

def writeToJSON(path, fileName, data):
    filePathNameWExt = './' + path + '/' + fileName + '.json'
    with open(filePathNameWExt, 'a') as fp:
        json.dump(data, fp)
因为不能向json添加数据,所以我认为最好使用pickle

可以使用pickle将对象读写到文件中。使用pickle,您可以读取并向文件中添加更多数据。如果您的数据是一个列表,您可以这样做:

# data is list in this example
def writeToJSON(path, fileName, data):
    filePathNameWExt = './' + path + '/' + fileName + '.json'
    # read old data
    with open(filePathNameWExt, 'rb') as handle:
       old_data = pickle.load(handle)
       save_data = old_data + data  # add the new data to old
       # wirte the new data
       with open(filePathNameWExt, 'wb') as handle:
        pickle.dump(save_data, handle, protocol=pickle.HIGHEST_PROTOCOL)

这就是JSON文件不好的原因之一,您无法覆盖单个值,它将始终覆盖整个文件。如果您同时运行多个命令,可能会出现争用情况,如果您不想切换到关系数据库,可以使用类似于
asyncio.Lock
的命令

lock=asyncio.lock()#记住导入asyncio
异步def写入到json(路径、文件名、数据):
带锁异步:#获取锁后,它将在上下文管理器结束时释放
文件路径='./'+path+'/'+fileName+'.json'
以fp形式打开(文件路径“w”):
json.dump(数据,fp)

什么是
writeToJSON
代码?路径/文件名/数据的内容是什么?你的问题到底是什么?你不能真的附加到JSON文件@ukaszKwieciński有更好的文件格式可以使用吗?你可以将数据列成列表或类似的东西,并使用pickle而不是@JustinWilker,最好是使用关系数据库,而不是通过将数据列为列表来完全确定您的意思。我只是想一次只保存一件东西到文件中。使用@jacobgalam提供的代码,我得到了错误