[英]How do I sort Python IndexError:List Index out of range when reading and writing with files
I'm working on a game in Python and at the end, scores are written to a file and then the top 5 scores are extracted from the file.我正在用 Python 开发一款游戏,最后,将分数写入文件,然后从文件中提取前 5 名分数。 This usually works perfectly fine but once I reset the high scores I get an Index error saying "the list index is out of range" Traceback (most recent call last):
这通常工作得很好,但是一旦我重置了高分,我就会收到一个索引错误,说“列表索引超出范围”回溯(最近一次调用):
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
How would I fix this我该如何解决这个问题
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))
In the external file, it is formatted so there is the score, followed by a comma, followed by a username.在外部文件中,它被格式化为分数,后跟逗号,后跟用户名。 For example:
例如:
100,exampleuser
The add_up functions are fine and just return the total score. add_up 函数很好,只返回总分。 I've tried to add placeholder scores to fix the problem, like
我试图添加占位符分数来解决这个问题,比如
1,Placeholder1
2,Placeholder2
3,Placeholder3
4,Placeholder4
5,Placeholder5
and this sometimes work but now is not working again.这有时有效,但现在不再有效。
After writing to the file its position is at the end - you can see that with leaders.tell()
.写入文件后,它的位置在末尾 - 您可以使用
leaders.tell()
看到它。 When you start reading, the for loop exits immediately because there are no more lines and dic
remains empty.当您开始阅读时,for 循环立即退出,因为没有更多行并且
dic
保持为空。 Later, scores
and names
are empty so you get an IndexError
when you try to access items.稍后,
scores
和names
为空,因此当您尝试访问项目时会收到IndexError
。
Before starting to read the file set it's position back to the beginning - if there is a header that you don't want skip the first line:在开始读取文件集之前,它的位置回到开头 - 如果有一个你不想跳过第一行的标题:
...
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.