以标头和值对的形式读取CSV数据

2024-06-02 08:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取一个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()

但我得到一个索引错误:

File "./load_calllogs.py", line 16, in readCsv data[row[column]] = {key: value for key, value in zip(headers, row[1:])} IndexError: list index out of range

这是我的CSV文件:

^{pr2}$

Tags: 文件csvkeyinimportfordatavalue
2条回答

一个^{}会帮你的。它会自动读入标题,然后根据该行将下面的每一行转换为字典。然后按名称而不是位置访问列:

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

这会给你:

^{2}$

您会注意到,“loadNumber”字段用作键,它也保留在字典中。在

试试这个代码。在

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)))

以下是输出(包含dict的列表):

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

相关问题 更多 >