我正在从包含以下数据的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
当我用一个循环迭代它时,我可以按行和只按下面的代码打印第1列数据。
file=open( path +"xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
t=line[0]
print t
根据上面的代码,我只能得到第一列。
如果我尝试打印第[1]行或第[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
请建议打印第2列或第3列的数据。
最佳答案
下面是我如何获得第2列和第3列:
import csv
path = 'c:\\temp\\'
file=open( path +"xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
t=line[1],line[2]
print(t)
结果如下:
('col2', 'col3')
('empId1', '241682-27638-USD-CIGGNT ')
('empId2', '241682-27638-USD-OCGGINT ')
('empId3', '241942-37190-USD-GGDIV ')
('empId4', '241942-37190-USD-CHYOF ')
('empId5', '241942-37190-USD-EQPL ')
('empId6', '241942-37190-USD-INT ')
('empId7', '242066-15343-USD-CYJOF ')
('empId8', '242066-15343-USD-CYJOF ')
('empId9', '242066-15343-USD-CYJOF ')
('empId10', '241942-37190-USD-GGDIV ')