On Monday November 12, 2007, Bryan Fodness wrote: > 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
Bryan, There are some blank lines in your file. When those lines are reached, line.split() returns an empty list, and therefore line.split()[0] is an IndexError. One way to rewrite this is as follows (untested): for line in f: pieces = line.split() if pieces: # non-empty line if pieces[0] == 'Field': field = int(pieces[-1]) elif pieces[0] == 'Leaf': fields[field] = pieces[-1] else: line = f.next() # I've left this here, but not sure # why you have it. The for loop # already advances from line to line Note as well that it is better to perform the split once per line (rather than recomputing it as you do in your original code). With regard, Michael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor