[Tutor] manipulating data

Tiger12506 keridee at jayco.net
Thu Nov 15 23:44:32 CET 2007


If you run this code

#
f = open('test1.mlc')
for line in f:
    print f.split()
#

You will see that about halfway through the file there is an empty list. I
assume that there was nothing on that line, in which case, there is no [0]
value.
In which case, you need to put in a try: except IndexError:  block like
this~

f = open('test1.mlc')
fields={}
for line in f:
    try:
        words = line.split()
        firstword = words[0]
    except IndexError: continue

    if firstword == 'Field':
        field = int(words[-1])
    elif firstword == 'Leaf':
        fields[field] = words[-1]


You will notice I made a few other changes. I changed it so line.split() is
assigned to a variable. That means I don't have to make the split() call
every time I want to check for a different word. The try except block just
fixes the problem you encountered. Also, I took out the last block-the else
block-because it is not necessary, and in fact will cause what you would
consider an error in the program. Calling f.next() will increment the line,
yes, but that is exactly for what the "for loop" is intended. The natural
conclusion of the for block is "finish the elif test and its block, then
execute code after it. Since there is no code after it indented to that
level, it automatically increments 'line' (line = f.next())

HTH,
JS


----- Original Message ----- 
From: "Bryan Fodness" <bryan.fodness at gmail.com>
To: "Alan Gauld" <alan.gauld at btinternet.com>
Cc: <tutor at python.org>
Sent: Monday, November 12, 2007 2:43 PM
Subject: Re: [Tutor] manipulating data


>I try this,
>
> f = open('TEST1.MLC')
>
> fields = {}
>
> for line in f:
>    if line.split()[0] == 'Field':
>        field = int(line.split()[-1])
>    elif line.split()[0] == 'Leaf':
>        fields[field] = line.split()[-1]
>    else:
>        line = f.next()
>
> and get,
>
> Traceback (most recent call last):
>  File "<pyshell#1>", line 1, in <module>
>    line.split()[0]
> IndexError: list index out of range
>
> I have attached my data file.
>


--------------------------------------------------------------------------------


> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list