Search code examples
pythonloopsfilerangetxt

IndexError: list index out of range only for loops?


I've been trying to make my program read a different line from a file each time the loop is completed. This works the first time but once the first loop is completed I am presented with IndexError: list index out of range. How can I fix this?

The file titled s is 18239 lines long and the file titled sp is 1000 lines long.

from itertools import count
import time
import webbrowser
import pynput
from pynput.keyboard import Key, Listener, Controller
import random
import string  
import secrets 



number = random.randint(0,18238)
number2 = random.randint(0,18238)
kb = Controller()
cout = 0
f = open('D:\Scripts\sp.txt', 'r')
fi = open('D:\Scripts\s.txt', 'r')
fil = open('D:\Scripts\s.txt', 'r')
while cout < 1000:
    linecount = random.randint(0,999)
    line = f.readlines()[linecount]
    lines = line.split()
    email = lines[0]
    password= lines[1]
    name = fi.readlines()[number]
    name2 = fil.readlines()[number2]
    firstname = name.rstrip("\n")
    lastname = name2.rstrip("\n")

Solution

  • now after some consideration I look at what was this issue, turns out python has issues re-reading files and so you have to put the readlines() outside the loop I ended up using read()

    Here's what I did to fix the issue this version of the code worked perfectly with no issues (no re-reading files guys python will cry), this version also keeps the purpose of the code (to read a specific random line each loop)

    import time
    import webbrowser
    import pynput
    from pynput.keyboard import Key, Listener, Controller
    import random
    import string  
    import secrets 
    
    
    
    
    kb = Controller()
    cout = 0
    f = open('D:\Scripts\sp.txt', 'r')
    fi = open('D:\Scripts\s.txt', 'r')
    fil = open('D:\Scripts\s.txt', 'r')
    lines = f.read().split("\n")   #outside the main loop to avoid index range error#
    name = fi.read().split("\n")   #outside the main loop to avoid index range error#
    while cout < 1000:
        linez = lines[random.randint(0,999)] # and then determine the line inside the loop#
        line = linez.split()
        email = line[0]
        password= line[1]
        names = name[random.randint(0,18238)] # and then determine the line inside the loop#
        namez = name[random.randint(0,18238)] # and then determine the line inside the loop#
        firstname = names.rstrip("\n")
        lastname = namez.rstrip("\n")