[Tutor] manipulating data
alan.gauld at btinternet.com
Mon Nov 12 23:22:43 CET 2007
> if line.split() == 'Field':
> field = int(line.split()[-1])
> IndexError: list index out of range
You have blank lines in the file, when you try to call split
on an empty string you get an empty list so trying to
index any element will result in an Index error.
That's why I suggested using exceptions, testing for
every possible error condition could take a long time
and be error prone. Unfortunately I guessed the wrong
error code and didn't realise you had some dross to
wade through first... so its a wee bit more complex.
Personally I'd use a flag to detect when field had
been found and set - ie set field to None and then
test for that changing, then test for Leaf as you do.
So I think your algorithm should be
for line in file
if 'Field' in line:
field = int(line.split()[-1])
elif 'Leaf' in line:
fields[field] = line.split()[-1]
But I think there's another problem in that you are
then overwriting the value of Leaf when I think you
are trying to build a list? I'm not 100% sure what
you are aiming for but hopefully its some help!
More information about the Tutor