I’ve run into a strange problem while writing some code for my personal use. I’ll let my code do the talking…
def getValues(self, reader):
for row in reader:
#does stuff
return assetName, efficiencyRating
def handleSave(self, assetName, reader):
outputFile = open(self.outFilename, 'w')
for row in reader:
#does other stuff
outputFile.close()
return
def handleCalc(self):
reader = csv.reader(open(self.filename), delimiter = ',', quotechar = '\"')
assetName, efficiencyRating = self.getValues(reader)
self.handleSave(assetName, reader)
This is just a portion of the code (obviously). The problem I’m having is in handleSave trying to loop through reader. It doesn’t appear to ever enter the loop? I’m really not sure what is happening. The loop in getValues behaves as expected.
Can someone explain what is happening? What have I done wrong? What should I do to fix this?
Once you’ve iterated through an iterator once, you can’t iterate through it again.
One way you can solve this is before you call
handleSave, rewind the file and create a new reader:Alternatively, you can read the data into a list:
And then iterate through
rowsrather thanreader.As a side note, the convention in Python is for names to be lowercase, separated by underscores, rather than camel case. (e.g.
get_valuesrather thangetValues,handle_saverather thanhandleSave)