简体   繁体   English

IndexError:列表索引超出文本文件的范围(Python)

[英]IndexError: list index out of range in text file (Python)

I have this bit of code that's inside a perpetual while loop, and whenever I try to get a random line from a text file, it occasionally throws an index error. 我的这段代码位于永久的while循环内,每当我尝试从文本文件中获取随机行时,它有时都会引发索引错误。 Can anybody help me with this? 有人可以帮我吗? I've already checked my text file and there are 452 lines inside. 我已经检查了我的文本文件,里面有452行。 At first I thought it was some number error so I reduced the upper bound, but the error keeps occurring. 起初我以为这是一些数字错误,所以我减小了上限,但错误不断发生。 The starred piece of code is what is causing the error. 出现星号的代码是导致错误的原因。

        if len(bank)==445:
            bank = []

        randinte = random.randint(1,450)
        samecheck(randinte, bank, 450)

        text_file = open("text.txt", "r")
        **line = text_file.readlines()[randinte]**
        twitter.update_status(
            status=line)
        text_file.close()
        bank.append(randinte)

EDIT: Thank you for all the help! 编辑:谢谢您的所有帮助! This is the code I ended up using and working. 这是我最终使用并工作的代码。 repopulate() is a method that populates bank from 1-451 sequentially. repopulate()是一种从1-451开始顺序填充库的方法。

        if len(bank)==5:
            bank = []
            repopulate()

        random.shuffle(bank)   
        text_file = open("text.txt", "r")
        lines = text_file.readlines()
        line = lines[bank.pop()]
        twitter.update_status(
            status=line)
        text_file.close()

Its not clear without seeing your text file why you might be getting these index errors, but its best to avoid hard-coding things like lengths of files if possible anyway. 在看不到文本文件的情况下不清楚为什么会出现这些索引错误,但是最好还是避免对文件长度之类的东西进行硬编码。 Another option would be to use the choice method in the random module to just choose a random line returned from readlines() , as below: 另一种选择是使用random模块中的choice方法来选择从readlines()返回的随机行,如下所示:

    if len(bank)==445:
        bank = []

    text_file = open("text.txt", "r")
    lines = text_file.readlines()

    line = random.choice(lines) # choose a random line

    twitter.update_status(
        status=line)
    text_file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM