亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

discord.py:如何從 json 文件中刪除一個值?

discord.py:如何從 json 文件中刪除一個值?

慕后森 2023-03-16 15:56:22
我的代碼:@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 excdiscord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str我想刪除特定值 f"{warnid}",但我不知道如何刪除此錯誤。以下是 json 文件的示例:{   305354423801217025: [      0145324124,      2142141244   ]{
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

您的錯誤在此行中,您嘗試刪除警告 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 Member

from discord.ext import commands

from 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)


查看完整回答
反對 回復 2023-03-16
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號