views:

89

answers:

3

I am struggling with something that must be one of those 'it is so obvious I am an idiot' problems. I have a csv file that I want to read in and use to create individual 'tables'. I have a variable (RID) that marks the beginning of a new 'table'.

I can't get my indicator variable (currentRow) to advance as I finish manipulating each line. You can see the print statements, currentRow remains equal to 0.
But if I use an assignment statement outside of the loop I can change the value of currentRow at will. The test assignment is to just understand where I am getting in the loop.

currentRow=0
test=0
theTables=defaultdict(list)
for line in csv.DictReader(open(r'c:\temp\testread.csv')):
    newTableKey=line['CIK']+'-'+line['RDATE']+'-'+line['CDATE']+'-'+line['FNAME']+' '+line['TID']

    if line['RID']=='1':
        test+=1 # I can get here
        if currentRow>int(line['RID']):
            print 'got here'

            theTables[oldTableKey]=theList
            test+=1  # I cannot get here
        theList=[]
    theList.append(line)
    currrentRow=int(line['RID'])
    print currentRow  #this value always prints at 0
    print int(line['RID']) #this prints at the correct value
    oldTableKey=newTableKey
A: 

One solution is to add the following somewhere inside the loop:

currentRow += 1

However, a better solution may be to use enumerable:

for currentRow, line in csv.DictReader..:
    stuff
knutin
currrentRow=int(line['RID'])
PyNEwbie
A: 

It looks to me like it's possible that theTables[oldTableKey]=theList could be executed with an uninitialized value of oldTableKey.

Peter Rowell
+7  A: 

In the line:

currrentRow=int(line['RID'])

you have three rs in currrentRow. Reduce them to just two, and things should improve.

Alex Martelli
Thanks Alex I knew it was one of these types of problems, public humiliation is good for the soul.Cheers
PyNEwbie
And run pylint or similar tools over the code so you don't have to ask Alex to review your code each time. ;-) See http://infinitemonkeycorps.net/docs/pph/#id3
Peter Hansen