Python CSV DictReader KeyError

时间:2016-07-11 20:57:33

标签: python csv iterator

I am getting an error, wherein the first iteration of the for loop in the third to last line in the code below line allows

print row['tick']

to be printed, but raises

KeyError: 'tick'

in subsequent iterations. I understand that this error means that the dictionary key 'tick' does not exist. I also tried printing row.keys() in place of row['tick'] and found that during the first iteration, all of they keys were consistently correct, but that on the beginning of the second iteration the values were somehow changed to some non-key values from the csv file. How could these values have been changed?

# In class Singleton
def __init__(self, source, currItem):
    self.reader = csv.DictReader(source)
    self.currItem = currItem
    # more code here 

def getReturnData(self):
    for row in self.reader:
        print row['tick']
        # more code here

# In main
with open('csvFileName') as source:
   for i in range(size):
       currItem = sheet.cell(row=i+2, column=1).value
       singleton = Singleton(source, currItem)
       totalReturnData.append(singleton.getReturnData())

EDIT

I seem to have fixed the problem by switching the with and the for lines like so:

for i in range(size):
    with open('csvFileName') as source:

Doing it like this seems to reset the reader object with every iteration of the for loop, which solves the problem I was having. But I think it is too hacky of a solution because it is running very slowly. I think this because the with open instruction seems to take a long time to execute. Is there any way I can properly reset my reader object, so that I only have to open my input file once?

0 个答案:

没有答案