[Tutor] manipulating data

Alan Gauld alan.gauld at btinternet.com
Tue Nov 13 00:55:14 CET 2007


The lesson here is not to try to do two things at once...

>         file.next()
>     TypeError: descriptor 'next' of 'file' object needs an argument

OK, My algorithm was meant to be pseudo code so file was
not intended to be taken literally, its just a marker for an open
file object.

> And, it is true that I am trying to build a list and not overwrite 
> the value.

OK, That adds a bit more tweaking...

>> 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.

That was before I went back to testing my own project....

>> So I think your algorithm should be
>>
>> for line in file
>>    if 'Field' in line:
>>       field = int(line.split()[-1])

and this was after - with no flag anywhere in sight! Oops.

I intended the if test to include a check for field == None...

if field == None and 'Field' in line:....

>>    elif 'Leaf' in line:
>>       fields[field] = line.split()[-1]
>>    else: file.next()
>>
>> 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?

So we need to create an empty list entry where we
define field and then append here, so my pseudo
code now becomes:

f = open('foo.dat')
for line in f:
    if field == None and 'Field' in line:
       field = int(line.split()[-1])
       fields[field] = []
    elif 'Leaf' in line:
       fields[field].append(line.split()[-1])
    else: f.next()

still untested I'm afraid, so it still may not work.

HTH,

Alan G.




More information about the Tutor mailing list