简体   繁体   English

我在 python 中收到此错误:IndexError:列表索引超出范围

[英]Im getting this error in python: IndexError: list index out of range

Im getting is error in python for some reason i don't understand how these are outside of the index when there are 7 elements to the file attack = user_stats.readlines()[2] IndexError: list index out of range由于某种原因,我在 python 中收到错误,当文件攻击 = user_stats.readlines()[2] IndexError: list index out of range 时,我不明白这些是如何在索引之外的

this is the code:这是代码:

with open(username + '.txt', 'r') as user_stats:
    level = user_stats.readlines()[1]
    attack = user_stats.readlines()[2]
    health = user_stats.readlines()[3]
    max_health = user_stats.readlines()[4]
    exp = user_stats.readlines()[5]
    money = user_stats.readlines()[6]

this is the txt file:这是 txt 文件:

username
1
1
25
25
0
0

The first call to readlines() reads the full file and reaches the end of the file.第一次调用 readlines() 读取整个文件并到达文件末尾。 Each subsequent call returns an empty string because you've already reached the end of the file.每个后续调用都会返回一个空字符串,因为您已经到达文件末尾。

There is no need to call readlines() multiple times.无需多次调用 readlines()。

well ive figured it out, idk that its the best way but it works好吧,我想通了,我知道这是最好的方法,但它确实有效

with open(username + '.txt', 'r') as user_stats:
    level = user_stats.readlines()[1]
with open(username + '.txt', 'r') as user_stats:
    attack = user_stats.readlines()[2]
with open(username + '.txt', 'r') as user_stats:
    health = user_stats.readlines()[3]
with open(username + '.txt', 'r') as user_stats:
    max_health = user_stats.readlines()[4]
with open(username + '.txt', 'r') as user_stats:
    exp = user_stats.readlines()[5]
with open(username + '.txt', 'r') as user_stats:
    money = user_stats.readlines()[6]

Firstly, as person above said the code should look something like that首先,正如上面的人所说,代码应该是这样的

with open('username.txt', 'r') as user_stats:
    lines = user_stats.readlines()
    level = lines[1]
    attack = lines[2]
    health = lines[3]
    max_health = lines[4]
    exp = lines[5]
    money = lines[6]
    print(username, level, attack, health, max_health, exp, money) #print to check if everything is right

Secondly, such things as stats should be stored inside objects but from what i can remember there are some limitations to python constructors, so i cannot really help much here.其次,诸如统计数据之类的东西应该存储在对象中,但据我所知,python 构造函数有一些限制,所以我在这里真的帮不上什么忙。 more about constructors更多关于构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM