![](/img/trans.png)
[英]Python Web Scraping error - Reading from JSON- IndexError: list index out of range - how do I ignore
[英]How do I sort Python IndexError:List Index out of range when reading and writing with files
我正在用 Python 開發一款游戲,最后,將分數寫入文件,然后從文件中提取前 5 名分數。 這通常工作得很好,但是一旦我重置了高分,我就會收到一個索引錯誤,說“列表索引超出范圍”回溯(最近一次調用):
File "/home/leo/Documents/Python/infinitest/infinitest.py", line 172, in <module>
scoreboard()
File "/home/leo/Documents/Python/infinitest/infinitest.py", line 147, in scoreboard
print("{0[0]} : {1[0]}\n{0[1]} : {1[1]}\n{0[2]} : {1[2]}\n{0[3]} : {1[3]}\n{0[4]} : {1[4]}".format(scores,names))
IndexError: list index out of range
我該如何解決這個問題
def scoreboard():
c = add_up1(False)
d = add_up2(False)
with open("/home/leo/Documents/Python/infinitest/hi2.txt", "a+") as leaders:
leaders.write('{},{}\n'.format(c,name1))
leaders.write('{},{}\n'.format(d,name2))
line=leaders.readline()
dic={}
for line in leaders:
data = line.split(",")
dic[int(data[0])] = data[1]
dic1={}
for key in sorted(dic.keys()):
dic1[key]=dic[key]
scores=list(dic1.keys())
names=list(dic1.values())
names =names[::-1]
scores= scores[::-1]
print("{0[0]} : {1[0]}\n{0[1]} : {1[1]}\n{0[2]} :{1[2]}\n{0[3]} : {1[3]}\n{0[4]} : {1[4]}".format(scores,names))
在外部文件中,它被格式化為分數,后跟逗號,后跟用戶名。 例如:
100,exampleuser
add_up 函數很好,只返回總分。 我試圖添加占位符分數來解決這個問題,比如
1,Placeholder1
2,Placeholder2
3,Placeholder3
4,Placeholder4
5,Placeholder5
這有時有效,但現在不再有效。
寫入文件后,它的位置在末尾 - 您可以使用leaders.tell()
看到它。 當您開始閱讀時,for 循環立即退出,因為沒有更多行並且dic
保持為空。 稍后, scores
和names
為空,因此當您嘗試訪問項目時會收到IndexError
。
在開始讀取文件集之前,它的位置回到開頭 - 如果有一個你不想跳過第一行的標題:
...
leaders.seek(0)
#_ = next(leaders) # skip header
for line in leaders:
data = line.split(",")
dic[int(data[0])] = data[1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.