Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading