python - 列表索引超出范围 - 但它不是
问题描述
获取 'level = line[3].rstrip()' 的列表索引超出范围错误。仔细检查了所有内容,我在显示之前打印了列表,并且显示了超过 4 个值(我试图获得第四个值)。下面的代码和回溯,谢谢!
代码:
async def lbcmd(ctx):
el = []
for file in os.scandir(lpath):
if file.path.endswith(".txt"):
with open(file, 'r') as f:
line = f.readlines()
level = line[3].rstrip()
xp = line[0].rstrip()
exp = {
"user": file.name.strip(".txt"),
"exp": xp,
"level": level
}
el.append(exp)
el.sort(reverse=True, key=operator.itemgetter('exp'))
desc = ("""
""")
for exp in el:
desc = desc + f"""Level {exp['level']} at {exp['exp']} exp - <@{exp['user']}>
"""
embed=discord.Embed(title=f"Level leaderboard", description=desc, color=0x2f3136)
await ctx.send(embed=embed)
追溯:
Traceback (most recent call last):
File "C:\Users\jakec\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\(A) Me\Coding\Python\jcjakec\Bots\conceptbot\conceptbot.py", line 144, in lbcmd
level = line[3].rstrip()
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\jakec\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\jakec\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\jakec\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range```
解决方案
推荐阅读
- python - 尝试创建看涨期权收益配置文件但不断收到此错误
- python - 将参数添加到表单集声明中
- firebase - Firebase 会取代我所有的云功能吗?
- python - ValueError: int() 以 10 为基数的无效文字:'' 当用户按下回车键时
- javascript - 为什么我的重定向代码不工作,但我的警报工作?请更正我的代码并检查
- swift - 过滤嵌套结构数组
- google-apps-script - Gmailapp 发送的邮件进入垃圾邮件文件夹
- javascript - 如何在函数内的 js 嵌套对象迭代中绑定 this。jQuery
- python - 如何解析 json 文件中的亚马逊评论数据?
- javascript - ECMAScript 中的标准函数参数如何评估为 AssignmentExpression?