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

who does IndexError: list index out of range appears ? i did some test still cant find out

Im working on a simple project python to practice , im trying to retreive data from file and do some test on a value
in my case i do retreive data as table from a file , and i do test the last value of the table if its true i add the whole line in another file

Here my data

 AE300812  AFROUKH  HAMZA  21  admis 
 AE400928  VIEGO  SAN  22  refuse 
 AE400599  IBN KHYAT  mohammed  22  admis 
 B305050  BOUNNEDI  SALEM  39  refuse 

here my code :

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

fichier = open("concours.txt","r")
fichier2 = open("admis.txt","w")
contenu = fichier.read()
tab = contenu.split()
for i in range(0,len(tab),5):
    if tab[i+4]=="admis":
        fichier2.write(tab[i]+" "+tab[i+1]+" "+tab[i+2]+" "+tab[i+3]+" "+tab[i+4]+" "+"\n")
fichier.close()

And here the following error :

if tab[i+4]=="admis":
IndexError: list index out of range

>Solution :

You look at tab[i+4], so you have to make sure you stop the loop before that, e.g. with range(0, len(tab)-4, 5). The step=5 alone does not guarantee that you have a full "block" of 5 elements left.

But why does this occur, since each of the lines has 5 elements? They don’t! Notice how one line has 6 elements (maybe a double name?), so if you just read and then split, you will run out of sync with the lines. Better iterate lines, and then split each line individually. Also, the actual separator seems to be either a tab \t or double-spaces, not entirely clear from your data. Just split() will split at any whitespace.

Something like this (not tested):

fichier = open("concours.txt","r")
fichier2 = open("admis.txt","w")
for line in fichier:
    tab = line.strip().split("  ")  # actual separator seems to be tab or double-space
    if tab[4]=="admis":
        fichier2.write(tab[0]+" "+tab[1]+" "+tab[2]+" "+tab[3]+" "+tab[4]+" "+"\n")

Depending on what you actually want to do, you might also try this:

with open("concours.txt","r") as fichier, open("admis.txt","w") as fichier2:
    for line in fichier:
        if line.strip().endswith("admis"):
            fichier2.write(line)

This should just copy the admis lines to the second file, with the origial double-space separator.

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