I can't wrap my head around generators fully, sometimes I happen to use them in a right way and sometimes I do not.
I am populating a db from a .csv file:
name, location
Tom, France
Doug, USA
Michael, UK
Here is my code:
def process_csv(filecsv):
f = open(filecsv)
f_csv = csv.reader(f)
headers = next(f_csv)
User = namedtuple('User', headers)
for user in f_csv:
user = [u.strip() for u in user]
user = User(*user)
yield user
def insert(cur, user):
u = list(user)[0] # it's a one-elem list so take it
cur.execute("INSERT INTO users (name, location) VALUES(%s, %s)",
(u.name, u.location))
if __name__ == '__main__':
cur = cxn.cursor()
user = process_csv(filecsv)
insert(cur, user)
When run this, only the first row got inserted into the db. Can you please advise how to fix it?