Attribute error on csv reader range

时间:2016-03-04 17:59:55

标签: python csv

I have the following code which should iterate though my csv file and create my json output. However, I am getting an attribute error on my exampledata object that no rows or row attribute exists. I know I can specify a specific row and column via [0][0] but need to dynamically call the row in the for loop vs specifically calling it. What can I do to fix this, is there a specific "row" or index I can use instead ie: exampledata[i][0]?

    payloads = []
    users_dict = {'users': []}
    exampleFile = open('zdfile-test.csv')
    exampleReader = csv.reader(exampleFile)
    exampleData = list(exampleReader)

    for row in range(1, exampleData.row):
      if exampleData(row)[2]:
        users_dict['users'].append(
            {
            "name": exampleData(row)[0],
            "email": exampleData(row)[2],
            "external_id": exampleData(row)[3],
            "details": exampleData(row)[4],
            "notes": exampleData(row)[5],
            "phone": exampleData(row)[6],
            "role": exampleData(row)[7],
            "organization_id": "",
            "tags": exampleData(row)[10],
            "password": exampleData(row)[11],
            "user_fields": {"nickname": exampleData(row)[1],"employee_phone_number": exampleData(row)[12],"employee_id": exampleData(row)[13],"employee_title": exampleData(row)[14],"employee_department": exampleData(row)[15],"employee_manager": exampleData(row)[16],"associate_id": exampleData(row)[17],"office_status": exampleData(row)[18],"customer_class": exampleData(row)[19],"primary_title": exampleData(row)[20],"associate_status": exampleData(row)[21],"joined_date": exampleData(row)[22],"e_mail": exampleData(row)[23],"isp_e_mail": exampleData(row)[24],"mobile": exampleData(row)[25],"office_name": exampleData(row)[26],"office_id": exampleData(row)[27],"office_city": exampleData(row)[28],"office_state": exampleData(row)[29],"office_phone": exampleData(row)[30],"region": exampleData(row)[31],"region_id": exampleData(row)[32],"region_type": exampleData(row)[33]}
        },
        {
            "external_id": exampleData(row)[3],
            "email": exampleData(row)[23],
        }
    )

1 个答案:

答案 0 :(得分:1)

As @GarrettR says, a list doesn't have a row attribute. You can do instead:

for row in range(1, len(exampleData)):
    #               ^^^

In the following line there will also be an error so you can do:

if exampleData[row][2]:
#             ^   ^