簡體   English   中英

我在 python 中收到此錯誤:IndexError:列表索引超出范圍

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

由於某種原因,我在 python 中收到錯誤,當文件攻擊 = user_stats.readlines()[2] IndexError: list index out of range 時,我不明白這些是如何在索引之外的

這是代碼:

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]

這是 txt 文件:

username
1
1
25
25
0
0

第一次調用 readlines() 讀取整個文件並到達文件末尾。 每個后續調用都會返回一個空字符串,因為您已經到達文件末尾。

無需多次調用 readlines()。

好吧,我想通了,我知道這是最好的方法,但它確實有效

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]

首先,正如上面的人所說,代碼應該是這樣的

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

其次,諸如統計數據之類的東西應該存儲在對象中,但據我所知,python 構造函數有一些限制,所以我在這里真的幫不上什么忙。 更多關於構造函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM