写入Discord bot的配置文件

2024-10-01 11:32:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件path命令jsondatadefbotarg
2条回答

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

lock = asyncio.Lock() # Remember to import asyncio

async def write_to_json(path, filename, data):
    async with lock: # acquiring the lock, it will be released at the end of the context manager 
        file_path = './' + path + '/' + fileName + '.json'
        with open(file_path, 'w') as fp:
            json.dump(data, fp)

如果要向文件中添加文本,则需要在open函数中使用'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)

相关问题 更多 >