简体   繁体   中英

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. Can anybody help me with this? I've already checked my text file and there are 452 lines inside. 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.

        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:

    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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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