Home > Enterprise >  Why am I getting IndexError: list index out of range error even though I have a proper list
Why am I getting IndexError: list index out of range error even though I have a proper list

Time:11-14

with open('Input','r') as f:
    while len(a)>0:

        a=f.readline()   #I am going to search for a command to execute in the txt file
        w_in_line=a.split(',') #words in line
        command_word_box=w_in_line[0].split()#I took the command word out of the line
        command_word=str(command_word_box[0])
        pat_name=w_in_line[0].replace(command_word,'')
        w_in_line[0]=pat_name
        for word in command_word_box:  #searching for commands
            if word=='create':
               create (w_in_line)
            else:
                continue

The text file is:

a
create Hayriye, 0.999, Breast Cancer, 50/100000, Surgery, 0.40
remove Hayriye

I am trying to read the text file and find a command and execute the command for each line therefore I seperated the first part before comma and took it in the command_word_box, then I took first word from it to detect my command and stored it in command_word but I keep getting

command_word=str(command_word_box[0])
IndexError: list index out of range

as output.

I can succesfully print the command_word_box and command_word, it gives the right outputs in list format just as I expected, command_word_box has 2 elements in it but apparently it doesn't take command_word_box[0] as a valid index for some reason.

CodePudding user response:

The problem happens when you read the last (blank!) line of the file. You check the condition len(a) before reading the next line, which is too early. Solution:

a=f.readline()
while len(a) > 0:
    w_in_line=a.split(',') #words in line
    # The rest of your loop here
    a=f.readline()

A much better approach is to use a for loop:

for a in f:
    w_in_line=a.split(',') #words in line
    # The rest of your loop here
  • Related