在读写文件时,如何对Python IndexError:List索引进行排序

我正在使用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

这有时可行,但现在不再起作用。

gxl6330395 回答:在读写文件时,如何对Python IndexError:List索引进行排序

写入文件后,其位置位于结尾-您可以使用leaders.tell()看到它。当您开始阅读时,因为没有更多的行并且dic仍然为空,所以for循环立即退出。以后,scoresnames为空,因此当您尝试访问项目时会得到IndexError

在开始读取文件集之前,它的位置是从头开始-如果您不希望头文件跳过第一行:

    ...
    leaders.seek(0)
    #_ = next(leaders)    # skip header
    for line in leaders:
        data = line.split(",")
        dic[int(data[0])] = data[1]
本文链接:https://www.f2er.com/2983896.html

大家都在问