将CSV数据读取为标题和值对

时间:2017-01-25 10:26:53

标签: python csv

我正在尝试读取CSV文件,并将标题作为键,将正文作为值对。 这是我的Python文件:

from pymongo import MongoClient
import requests

import csv
import sys
data = {}

def readCsv(csvFile, column):
    with open(csvFile, "rb") as infile:
        reader = csv.reader(infile)
        headers = next(reader)[1:]
        for row in reader:
            data[row[column]] = {key: value for key, value in zip(headers, row[1:])}

def readCalllogs():
    for loanNumber in data:
        logDetail = data[loanNumber]
        print logDetail
        resp = requests.post('http://localhost:3500/api/v1/call_logs', json=logDetail)
        if resp.status_code != 201:
                print resp.status_code
        else:
            print logDetail

def writeYAMLFile():
    for loan in loans:
        print loan["assignedTo"]


def loadCalllogsFromCsv():
    readCsv("calllogs.csv", 0)
    readCalllogs()

def main():
    loadCalllogsFromCsv()


if __name__ == "__main__":
    main()

但是我收到了一个索引错误:

  

文件“./load_calllogs.py”,第16行,在readCsv中       data [row [column]] = {key:key的值,zip中的值(header,row [1:])}   IndexError:列表索引超出范围

这是我的CSV文件:

loanNumber,date,contactStatus,contactRelation,contactName,response,tenantId,actionDate,action,assignedTo,remarks,caller
1,,CONNECTED,SELF,NAME1,RESPONSE1,,,FIELD_PTP,ASSIGN1,REMARK1,CALLER1
2,,WRONG_NUMBER,SELF,NAME2,RESPONSE2,,,MEET_GUARANTOR,ASSIGN2,REMARK2,CALLER2
3,,CONNECTED,WIFE,NAME3,RESPONSE3,,,FIELD_PTP,ASSIGN3,REMARK3,CALLER3
4,,NO_RESPONSE,HUSBAND,NAME4,RESPONSE4,,,MEET_GUARANTOR,ASSIGN4,REMARK4,CALLER4
5,,CONNECTED,SON,NAME5,RESPONSE5,,,VISIT_CUSTOMER,ASSIGN5,REMARK5,CALLER5
6,,CONNECTED,SON,NAME6,RESPONSE6,,,VISIT_CUSTOMER,ASSIGN6,REMARK6,CALLER6

2 个答案:

答案 0 :(得分:1)

试试这段代码。

file = "your_file.csv"

my_list = []

with open(file, mode='r') as input_file:
    rows = []
    for row in input_file:
        rows.append(row.rstrip('\n').split(","))
    keys = rows[0]
    for values in rows[1:]:
        my_list.append(dict(zip(keys, values)))

这是输出(包含dicts的列表):

  

[{'actionDate':'','来电':'CALLER1','contactStatus':'已连接','contactName':'NAME1','tenantId':'','loanNumber':'1' ,'action':'FIELD_PTP','contactRelation':'SELF','assignedTo':'ASSIGN1','备注':'REMARK1','date':'','response':'RESPONSE1'},{ 'actionDate':'','来电':'CALLER2','contactStatus':'WRONG_NUMBER','contactName':'NAME2','tenantId':'','loanNumber':'2','action': 'MEET_GUARANTOR','contactRelation':'SELF','assignedTo':'ASSIGN2','备注':'REMARK2','date':'','response':'RESPONSE2'},{'actionDate':' ','来电':'CALLER3','contactStatus':'CONNECTED','contactName':'NAME3','tenantId':'','loanNumber':'3','action':'FIELD_PTP',' contactRelation':'WIFE','assignedTo':'ASSIGN3','备注':'REMARK3','date':'','response':'RESPONSE3'},{'actionDate':'','来电' :'CALLER4','contactStatus':'NO_RESPONSE','contactName':'NAME4','tenantId':'','loanNumber':'4','action':'MEET_GUARANTOR','contactRelation':'HUSBAND ', '分配edTo':'ASSIGN4','备注':'REMARK4','日期':'','响应':'RESPONSE4'},{'actionDate':'','来电':'CALLER5','contactStatus' :'CONNECTED','contactName':'NAME5','tenantId':'','loanNumber':'5','action':'VISIT_CUSTOMER','contactRelation':'SON','assignedTo':'ASSIGN5 ','评论':'REMARK5','日期':'','响应':'RESPONSE5'},{'actionDate':'','来电':'CALLER6','contactStatus':'已连接', 'contactName':'NAME6','tenantId':'','loanNumber':'6','action':'VISIT_CUSTOMER','contactRelation':'SON','assignedTo':'ASSIGN6','备注' :'REMARK6','日期':'','回复':'RESPONSE6'}]

答案 1 :(得分:1)

DictReader可以帮到你。它会自动读取标题,然后将每个后续行转换为基于该行的字典。然后按名称访问列,而不是它们的位置:

import csv

data = {}

def readCsv(csvFile, column):
    with open(csvFile, "rb") as infile:
        reader = csv.DictReader(infile)

        for row in reader:
            data[row[column]] = row

readCsv("calllogs.csv", 'loanNumber')
print data

这会给你:

{'1': {'actionDate': '', 'loanNumber': '1', 'assignedTo': 'ASSIGN1', 'caller': 'CALLER1', 'tenantId': '', 'action': 'FIELD_PTP', 'remarks': 'REMARK1', 'contactName': 'NAME1', 'contactRelation': 'SELF', 'date': '', 'response': 'RESPONSE1', 'contactStatus': 'CONNECTED'}, '3': {'actionDate': '', 'loanNumber': '3', 'assignedTo': 'ASSIGN3', 'caller': 'CALLER3', 'tenantId': '', 'action': 'FIELD_PTP', 'remarks': 'REMARK3', 'contactName': 'NAME3', 'contactRelation': 'WIFE', 'date': '', 'response': 'RESPONSE3', 'contactStatus': 'CONNECTED'}, '2': {'actionDate': '', 'loanNumber': '2', 'assignedTo': 'ASSIGN2', 'caller': 'CALLER2', 'tenantId': '', 'action': 'MEET_GUARANTOR', 'remarks': 'REMARK2', 'contactName': 'NAME2', 'contactRelation': 'SELF', 'date': '', 'response': 'RESPONSE2', 'contactStatus': 'WRONG_NUMBER'}, '5': {'actionDate': '', 'loanNumber': '5', 'assignedTo': 'ASSIGN5', 'caller': 'CALLER5', 'tenantId': '', 'action': 'VISIT_CUSTOMER', 'remarks': 'REMARK5', 'contactName': 'NAME5', 'contactRelation': 'SON', 'date': '', 'response': 'RESPONSE5', 'contactStatus': 'CONNECTED'}, '4': {'actionDate': '', 'loanNumber': '4', 'assignedTo': 'ASSIGN4', 'caller': 'CALLER4', 'tenantId': '', 'action': 'MEET_GUARANTOR', 'remarks': 'REMARK4', 'contactName': 'NAME4', 'contactRelation': 'HUSBAND', 'date': '', 'response': 'RESPONSE4', 'contactStatus': 'NO_RESPONSE'}, '6': {'actionDate': '', 'loanNumber': '6', 'assignedTo': 'ASSIGN6', 'caller': 'CALLER6', 'tenantId': '', 'action': 'VISIT_CUSTOMER', 'remarks': 'REMARK6', 'contactName': 'NAME6', 'contactRelation': 'SON', 'date': '', 'response': 'RESPONSE6', 'contactStatus': 'CONNECTED'}}

您将注意到' loadNumber`字段用作键,它也留在字典本身。