[Tutor] IndexError: list index out of range

Peter Otten __peter__ at web.de
Thu Jun 26 11:23:55 CEST 2014


Myunggyo Lee wrote:

> I'm trying to figure out the reason of error but i couldn't find it.
> first imports short.txt(is attached to this mail)
> and read in dictionary named gpdic1
> 
> 
> Traceback (most recent call last):
>   File "/home/ercsb/test.py", line 11, in <module>
>     hgene = lines[1]
> IndexError: list index out of range


> # -*- coding: utf-8 -*-
> import string, os, sys, time, glob
> 
> inf2 =open('short.txt','r')
> 
> gpdic1={}
> while 1:
>         line= inf2.readline()
>         if not line: break

Add a print statement here to see the problem:

          print "processing", repr(line)

Hint: you have an empty line in your data, so:
>>> lines = "\n"[:-1].split(",")
>>> lines
['']
>>> lines[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

A possible fix is to skip empty lines

for line in open("short.txt"):
    line = line.strip()
    if not line:
        continue # line contains only whitespace, move on to the next line
    ... # your code

>         lines = line[:-1].split(',')
> 
>         hgene = lines[1]
>         chr1 = lines[4]
>         hgstart = lines[5]
>         hgstop = lines[6]
>         tgene = lines[7]
>         chr2 = lines[10]
>         tgstart = lines[11]
>         tgstop = lines[12]

Note that the following replaces the data of the previous line; once the 
while loop has finished you have lost all data except that taken from the 
last line in the file.

>         gpdic1["hgene"] = hgene
>         gpdic1["chr1"] = chr1
>         gpdic1["hgstart"] = hgstart
>         gpdic1["hgstop"] = hgstop
>         gpdic1["tgene"] = tgene
>         gpdic1["chr2"] = chr2
>         gpdic1["tgstart"] = tgstart
>         gpdic1["tgstop"] = tgstop




More information about the Tutor mailing list