I’m writing some python code that’s supposed to parse a CSV file. Calculate the mean value of a specific row and then send an email to recipients based on the values of one row in the CSV file. My code is as follows, I’ve removed the email sending code for now and replaced it with a print statement:
def main():
#smtp_instance = smtplib.SMTP('localhost')
ldap_file = open('ldaps.csv','rU')
ldap_data=csv.DictReader(ldap_file)
scores = list(int(d['score']) for d in ldap_data)
average_score = sum(scores) / len(scores)
print average_score
for rows in ldap_data:
ldap = rows['ldap']
fullname = rows['fullname']
firstname = fullname.split(' ')[0]
location = rows['location']
score = rows['score']
if int(score) < average_score:
score_msg = 'below'
else:
score_msg = 'above'
print 'Hi ' + firstname + '\n'\
'You got a ' + score + '% on your Final Exam.'\
'The average score was ' + average_score + '.'\
'This means that you scored ' + score_msg + ' average.'
if __name__ == '__main__':
main()
When I run this it prints the average_score value. But the code never gets to the for..loop. It seems that I can’t call a list comprehension on the dict and then iterate on the same dict. Any idea what I’m doing wrong and how I can fix it?
The reader objects returned by the
csvmodule behave as generators, they can only be iterated over once. If you want a real list that you can iterate repeatedly, you have to create on explicitly: