读取时出现简单的CSV文件错误

时间:2018-02-19 03:55:03

标签: python file csv

我是Python编程的新手,我想更多地了解python的内部工作,为什么我的代码会出现这个错误:

代码

with open('countries.csv','r') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print(row[1])

错误:

Traceback (most recent call last):
2
  File "/DS/main.py", line 12, in <module>
china
    print(row[1])
china
IndexError: list index out of range
germany
us
japan
india
us
china
india
japan

Process finished with exit code 1

我的CSV文件由一个简单的逗号(分隔符)分隔,它显示正确的输出,但是提到了错误?

4 个答案:

答案 0 :(得分:0)

代码应为

with open('countries.csv','r') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
    print(row[0])

答案 1 :(得分:0)

虽然我不能确定没有csv文件的SPECIFIC内容,但我建议numpy.genfromtxt此外,它可能只是你不需要索引'行',它可能是一维数据集(假设您不认为字符串本身是另一个维度)。

所以:

from numpy import genfromtxt
acm_data = genfromtxt("countries.csv", delimiter=',', names="country")
countries = acm_data["country"]
for country in countries:
    print(country)

编辑:

from numpy import genfromtxt
dat = genfromtxt("countries.csv", delimiter=',', names="c1, c2, c3, c4, c5")
countries = sum([tuple(dat["c%d" %i]) for i in range(1,6)], ())
for country in countries:
    print(country)

或者,如果您想将其保留为表格,请将countries = sum([tuple(dat["c%d" %i]) for i in range(1,6)], ())替换为countries = [list(dat["c%d" %i]) for i in range(1,6)],并将print(country)替换为print(country[0])print(country[1])(如果您要打印)分别是第一个国家或第二个国家。

答案 2 :(得分:0)

您的数据可能包含少于两个单元格的空行或行。要识别它们,请使用try / except:

for row in readCSV:
    try:
        print(row[1])
    except IndexError:
        print('Bad row:', row)

更新

您的CSV文件似乎有空行,转换为空行[]。要过滤掉那些空行,可以采用以下方法:

with open('countries.csv','r') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    readCSV = (row for row in readCSV if row) # Filter out empty rows
    for row in readCSV:
        print(row[1])

答案 3 :(得分:0)

@Hai Vu之后: 第二种方法可能是:

代码:

以open('countries.csv','r')作为csvfile:

    readCSV = csv.DictReader(csvfile, delimiter=',')
    for row in readCSV:
        print(row)