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()
len()of thereadlines()result to pick a random number?readlines()the method to return the line in a text file?lines = text_file.readlines()thenrandinte = random.randint(len(lines))andline = lines[randinte]. That way at least line 0 can be picked too.