在Python中从CSV文件读取数据 [英] Reading data from a CSV file in Python

查看:1295
本文介绍了在Python中从CSV文件读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从包含以下数据的CSV文件(xyz.CSV)中读取数据:

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

当我使用循环对其进行迭代时,我可以按以下代码逐行打印数据,并且仅打印column1数据.

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.

如果我尝试打印line [1]或line [2],则会出现以下错误.

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

请建议打印第2列或第3列的数据.

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)

以下是结果:

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

这篇关于在Python中从CSV文件读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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