簡體   English   中英

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

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

我的這段代碼位於永久的while循環內,每當我嘗試從文本文件中獲取隨機行時,它有時都會引發索引錯誤。 有人可以幫我嗎? 我已經檢查了我的文本文件,里面有452行。 起初我以為這是一些數字錯誤,所以我減小了上限,但錯誤不斷發生。 出現星號的代碼是導致錯誤的原因。

        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)

編輯:謝謝您的所有幫助! 這是我最終使用並工作的代碼。 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()

在看不到文本文件的情況下不清楚為什么會出現這些索引錯誤,但是最好還是避免對文件長度之類的東西進行硬編碼。 另一種選擇是使用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