python打开并读取csv文件_在Python中从CSV文件读取数据

1586010002-jmsa.png

I am reading data from a CSV file (xyz.CSV) which contains below data:

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

When I am iterating it with a loop I am able to print the data row wise and and only column1 data by the below code.

file=open( path +"xyz.CSV", "r")

reader = csv.reader(file)

for line in reader:

t=line[0]

print t

By the above code I can only get the first column.

If I try to print line[1] or line[2] it gives me the below error.

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

Please suggest for printing the data of column2 or column3.

解决方案

Here is how I've got 2nd and 3rd columns:

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)

Here is the results:

('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 ')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值