discord.py:如何从 json 文件中删除一个值?

我的代码:


@bot.command()

async def delwarn(ctx, member: discord.Member = None, warnid = None):

    if member:


          with open('warns.json', 'r') as fcheckifthere:

                checkifthere = json.load(fcheckifthere)

          if f'{member.id}' in checkifthere.keys():


                amount = len(checkifthere[f'{member.id}'])

                if f'{warnid}' in checkifthere[f'{member.id}']:

                    if not amount == 1:

                        

# i want to delete the value f"{warnid}"   

                         del checkifthere[f'{member.id}'][f'{warnid}']

                          with open('warns.json', 'w+') as fcheckifthere:

                              json.dump(checkifthere, fcheckifthere, sort_keys=True, indent=4)

错误:



Traceback (most recent call last):

  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke

    await ctx.command.invoke(ctx)

  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke

    await injected(*ctx.args, **ctx.kwargs)

  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped

    raise CommandInvokeError(exc) from exc

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str

我想删除特定值 f"{warnid}",但我不知道如何删除此错误。


以下是 json 文件的示例:


{

   305354423801217025: [

      0145324124,

      2142141244

   ]

{


慕后森
浏览 111回答 1
1回答

泛舟湖上清波郎朗

您的错误在此行中,您尝试删除警告 ID:del checkifthere[f'{member.id}'][f'{warnid}']checkifthere[f'{member.id}']是一个列表,您提供的索引是一个字符串。列表索引必须是整数,所以你有一个错误。删除列表元素的最简单方法是使用list.remove(element):checkifthere[str(member.id)].remove(warnid)此外,您不需要f strings,您可以使用str()将整数和浮点数转换为字符串。通过一些重构,您的命令如下所示:from discord import Memberfrom discord.ext import commandsfrom json import load, dump@bot.command()async def delwarn(ctx, member: Member = None, warn_id: str = None):    if not member:        return    with open('warns.json', 'r') as file:        data = load(file)        member_id = str(member.id)    if not member_id in data.keys():        return    if warn_id in data[member_id] and not len(data[member_id]) == 1:        with open('warns.json', 'w') as file:            data[member_id].remove(warn_id)            dump(data, file, sort_keys=True, indent=4)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python