如何使用Python的CSV DictReader解析CSV输出?

时间:2015-11-03 11:12:12

标签: python csv

我已经集成了Salesforce的Bulk API来获取我的Python项目中的记录。使用'Content-Type': 'text/csv; charset=UTF-8'标头,它将返回CSV输出。

"Id","Name","CreatedById","Salary","Base_Salary","Type","Pay_cycle","Description","Code"
"a0u90000003R4Y9AAK","Freelance Hadoop developer","005900000039GMdAAM","","","","","",""
"a0u90000003R5UPAA0","Senior Hadoop developer","005900000039GMdAAM","","","","","",""
"a0u90000003R5V3AAK","Freelance Webmaster","005900000039GMdAAM","","","","","",""
"a0u90000004ZMUwAAO","Full-Stack Web Developer - PHP and Python","005900000039GMdAAM","","","","","",""

现在,如果不将其存储在CSV文件中,我想将这些记录放在我的Db中。

DictReader是获取字段值的非常好且简单的解决方案,但我想它只适用于(CSV)文件。

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

我正在尝试一些东西,但我不喜欢它。参见

objects = []
for line in iter(csv_data.splitlines()):
    # Split by separator
    data = line.split(",")
    # Remove double quotes around the field value
    objects.append([i[1:-1] for i in data])

这样做最优雅的方式是什么?

1 个答案:

答案 0 :(得分:3)

您可以将csv字符串包装到io.StringIO对象中。然后,这将与csv模块完美配合:

data_str = '''"Id","Name","CreatedById","Salary","Base_Salary","Type","Pay_cycle","Description","Code"
"a0u90000003R4Y9AAK","Freelance Hadoop developer","005900000039GMdAAM","","","","","",""
"a0u90000003R5UPAA0","Senior Hadoop developer","005900000039GMdAAM","","","","","",""
"a0u90000003R5V3AAK","Freelance Webmaster","005900000039GMdAAM","","","","","",""
"a0u90000004ZMUwAAO","Full-Stack Web Developer - PHP and Python","005900000039GMdAAM","","","","","",""'''

# in python 2 you need to decode the string before passing it to StringIO
data_io = io.StringIO(data_str.decode('utf-8'))
## this is not needed in python 3
# data_io = io.StringIO(data_str)

reader = csv.DictReader(data_io)
for row in reader:
    print row['Id'], row['Name']