Skip to content
Advertisement

how to import data from a excel list into a loop for a api python

I am connecting an API and everything is going fine, now I have one problem, I have a data excel list like this:

Name Secondname Age
alex test 2020-02-03
pieter guy 2020-04-04

in my script i have a variable called: name.

name = data.name   
secondname= data.secondname    
age = data.age     

Now i want to make a script that takes everyloop 1 line of data.

so loop 1:

ALEX TEST 2020-02-03

loop 2:

PIETER GUY 2020-04-04

and stores it into the variable: name, second name, age so I can send it with my payload

can someone please help me, I tried pandas and just the CSV module but it’s just not working?

current script:

import csv
with open('Map3.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['Name'])

error:

Traceback (most recent call last): File “D:/printtest.py”, line 5, in print(row[‘Name;’]) KeyError: ‘Name;’

here is my excel with error:

enter image description here

Advertisement

Answer

The problem you are having in the code is that the the dictionaries keys are case sensitive. You’re trying to access row['NAME'] but the code is looking for row['Name;']. That’s the reason you are having a KeyError. To access every column in the file, you have to use the same column name without the delimiter character.

Here is the code with the problem solved:

import csv

with open('Map3.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
       name = row['NAME']
       secondname = row['SECONDNAME']
       age = row['AGE']

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement