如何正确读取csv并输入到列表中? [英] How to correctly read csv and input into list?

查看:297
本文介绍了如何正确读取csv并输入到列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将.csv文件中的一堆数据读取为以下格式的数组: [[a,b,c,d],[e,f,g,h],...]

I am trying to read a bunch of data in .csv file into an array in format: [ [a,b,c,d], [e,f,g,h], ...]

运行下面的代码,当我用空格('')打印条目时,我访问元素的方式不正确,因为它停在第一个空格('')处. 例如,如果商务",快速公司","Youtube",快速公司"是第10个条目...当我打印以下内容时,我会在单独的行上得到: 业务,快速 公司,YouTube,快速公司

Running the code below, when I print an entry with a space (' ') the way I'm accessing the element isn't correct because it stops at the first space (' '). For example if Business, Fast Company, Youtube, fastcompany is the 10th entry...when I print the below I get on separate lines: Business,Fast Company,YouTube,FastCompany

关于如何获得结果的任何建议:[[a,b,c,d],[业务,快速公司,Youtube,快速公司],[e,f,g,h],...]?

Any advice on how to get as the result: [ [a,b,c,d], [Business, Fast Company, Youtube, fastcompany], [e,f,g,h], ...]?

import csv

partners = []
partner_dict = {}
i=9
with open('partners.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        partners.append(row)

    print len(partners)

    for entry in partners[i]:
        print entry

推荐答案

delimiter参数指定使用哪个字符将文件的每一行拆分为单独的值.由于您传递的是''(一个空格),因此读者正在拆分空格.

The delimiter argument specifies which character to use to split each row of the file into separate values. Since you're passing ' ' (a space), the reader is splitting on spaces.

如果这确实是一个逗号分隔的文件,请使用','作为分隔符(或只保留delimiter参数,它将默认为',').

If this is really a comma-separated file, use ',' as the delimiter (or just leave the delimiter argument out and it will default to ',').

此外,竖线字符对于引号字符来说是一个不寻常的值.输入文件中包含代替引号的管道真的是真的吗?您提供的样本数据都不包含引号.

Also, the pipe character is an unusual value for the quote character. Is it really true that your input file contains pipes in place of quotes? The sample data you supplied contains neither pipes nor quotes.

这篇关于如何正确读取csv并输入到列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆