简体   繁体   English

如何在读取和写入文件时对 Python IndexError:List Index out of range 进行排序

[英]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.稍后, scoresnames为空,因此当您尝试访问项目时会收到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.

相关问题 Python Web 抓取错误 - 从 JSON 读取 - IndexError:列表索引超出范围 - 我该如何忽略 - Python Web Scraping error - Reading from JSON- IndexError: list index out of range - how do I ignore IndexError: list index out of range 我没有读取文件,我的列表似乎没有超出范围 - IndexError: list index out of range i am not reading files and my list does not seem to be out of range Python 3.4-XML解析-IndexError:列表索引超出范围-如何找到XML范围? - Python 3.4 - XML Parse - IndexError: List Index Out of Range - How do I find range of XML? 如何修复 Python 中的“IndexError: list index out of range” - How do you fix 'IndexError: list index out of range' in Python 如何解决 IndexError: list index out of range? - how do I resolve IndexError: list index out of range? 如何解决 IndexError:列表索引超出范围 - How do I resolve IndexError: list index out of range 如何解决错误“IndexError:列表索引超出范围” - How do I solve the error, "IndexError: list index out of range" 如何修复IndexError:Python中的字符串索引超出范围 - How do I fix IndexError: string index out of range in python IndexError:列表分配索引超出范围Python 3这是什么意思,我该如何解决? - IndexError: list assignment index out of range Python 3 What does this mean and how do I fix it? IndexError:列表索引超出了CSV文件读取python中的范围 - IndexError: list index out of range in CSV file reading python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM