【发布时间】:2015-01-10 06:27:38
【问题描述】:
我正在从包含以下数据的 CSV 文件 (xyz.CSV) 中读取数据:
col1,col2,col3,col4
name1,empId1,241682-27638-USD-CIGGNT ,1
name2,empId2,241682-27638-USD-OCGGINT ,1
name3,empId3,241942-37190-USD-GGDIV ,2
name4,empId4,241942-37190-USD-CHYOF ,1
name5,empId5,241942-37190-USD-EQPL ,1
name6,empId6,241942-37190-USD-INT ,1
name7,empId7,242066-15343-USD-CYJOF ,3
name8,empId8,242066-15343-USD-CYJOF ,3
name9,empId9,242066-15343-USD-CYJOF ,3
name10,empId10,241942-37190-USD-GGDIV ,2
当我使用循环对其进行迭代时,我可以通过以下代码逐行打印数据,并且仅打印 column1 数据。
file=open( path +"xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
t=line[0]
print t
通过上面的代码我只能得到第一列。
如果我尝试打印 line[1] 或 line[2] 它会给我以下错误。
file=open( path +"xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
t=line[1],[2]
print t
t=line[1],line[2]
IndexError: list index out of range
请建议打印 column2 或 column3 的数据。
【问题讨论】:
-
考虑使用
csv.reader。 -
csv 文件是否也包含
xyz.CSV col1,col2,col3,col4。如果是这种情况,那么第一行只包含一个元素,即['xyz.CSV'],然后当您尝试访问 [1] 之后它会失败。