Thread: IndexError

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12

    IndexError


    Hi,
    Can someone find the bug in this code!

    Code:
    >>> strLine='#'
    >>> dict={}
    >>> fin=open('c:\\python23\\scripts\\','r')
    >>> while strLine!='':
    ... 		strLine=fin.readline()
    ... 		if ''!=strLine:
    ... 			z=strLine.split('||')
    ... 			strKey=z[0]
    ... 			strValue=z[1][:-1]
    ... 			dict[strKey]=strValue
    ... 		else:raise IndexError
    The error that I get is
    Code:
    Traceback (most recent call last):
      File "<interactive input>", line 6, in ?
    IndexError: list index out of range
    Can anyone spot the error?????

    Many thanks,
    Subha
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    yes, on line 6 you assume split produces what you want and don't handle when z has len == 1. That's what your traceback reported

    Code:
    >>> a = "hello".split("x")
    >>> a
    ['hello']
    >>> a = "hellox".split("x")
    >>> a
    ['hello', '']
    >>>
    grimey
    Last edited by Grim Archon; November 15th, 2004 at 04:43 AM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    624
    Rep Power
    34
    I'll try

    Code:
    >>> dict={}
    This rebinds the builtin function "dict"...

    Code:
    >>> fin=open('c:\\python23\\scripts\\','r')
    This seems to be trying to open a directory as if it was a file - I'd expect you to get an IOError here.

    Code:
    >>> while strLine!='':
    This could be written as "while strLine:" because an empty string is evaluates as "False" for these kinds of tests, but it's just for ease of reading, and not really a problem.

    Code:
    ... 		if ''!=strLine:
    The same here with "if not strLine:"

    Code:
    ... 			z=strLine.split('||')
    ... 			strKey=z[0]
    ... 			strValue=z[1][:-1]
    Somewhere in here, strLine probably doesn't split into two pieces, so z[1] will not exist. At the start of the program, you say "strLine = '#'", then doing a split('||') will result in a single-item list, for instance.

    You might want error checking here, or you might want to check the file you are reading for blank lines, etc.

    Code:
    ... 			strValue=z[1][:-1]
    This... well, have you tried it? It returns an empty string all the time, which is probably not what you want.
    It takes the list z, then takes the single item at index 1.
    Then, from that, it removes the last item from the string.

    Code:
    ... 			dict[strKey]=strValue
    ... 		else:raise IndexError
    Here, you are saying:
    "While the line is not blank:
    Read a line from the file
    if the line is blank raise an IndexError
    "

    Which seems like a strange error to raise...


    It looks like you are reading a file like this:
    Code:
    key1||value1
    key2||value2
    So you could try something like:

    Code:
    mydict = {}
    fin = file('c:\\python23\\myfile.txt', 'rb')
    
    for line in fin:
        if line:
            key, value = line.split('||')
            mydict[key] = value


    Or, if the file might have some lines in the wrong format that you want to ignore, this might be more useful:

    Code:
    mydict = {}
    fin = file('c:\\python23\\myfile.txt', 'rb')
    
    for line in fin:
        if line:
            try:
                key, value = line.split('||')
                mydict[key] = value
    
            except ValueError:
                print "This line is not in the right format:"
                print line
                print
  6. #4
  7. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    .... plus all the errors sfb mentioned
  8. #5
  9. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    Code:
    fin=open('c:\\python23\\scripts\\','r')
    Can't see how you managed to enter this without getting an exception!
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    Nooooooo that wasn't an error of the filename....a typo maybe.... I forgot to add the filename ...while typing in the query...I didn't paste the that particular file opening line .... and so I didn't receive any error there....thanks both of u....let me see if things work fine....


    Thanks,
    Subha
  12. #7
  13. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    As you now know it is more helpful to you and us if you post real code, there is no point making up stuff by pasting it together.

    grimey
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    Always post the real code....this time I guess was being too smart...anyway....I'll keep ur sarcastic statement in mind!!!!

    Thanks,
    Subha
  16. #9
  17. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
  18. #10
  19. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    Yet another version ,

    Code:
    #!/usr/bin/env python
    
    matrix = {}
    
    for line in file('C:\Python23\myfile.txt'):
        if '||' in line:
            key, value = line.split('||')
            matrix[key] = value
    This time, I do a simple check to see if the '||' characters are in line - so the split should go ahead without a glitch. If we can't split (because the '||' characters can't be found) then it just ignores the line.

    Simple enough,

    Mark.
    programming language development: www.netytan.com Hula

  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    Thanks sfb....my problem is solved...thanks for the beautiful explanation!

    Subha
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2004
    Location
    Bombay, India
    Posts
    159
    Rep Power
    12
    Thanks Mark .... you've reduced the lines of code drastically...and yes readable too ....thats great!


    Subha

IMN logo majestic logo threadwatch logo seochat tools logo