如何从Python中的.csv文件中获取第三个字段?

时间:2013-09-28 11:00:14

标签: python python-2.7

我的文件abc.csv包含:

a,b,c,d,e
f,g,h,i,j

我的代码如下; for循环没有给我所需的输出,即c h

for line1 in open('abc.csv', 'r') :
    result = line1.split(",")[2]
    print result    

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:-1)

实际上我验证了你的代码工作得很好。但无论如何,您应该更喜欢csv模块来解析CSV文件:

import csv

with open('abc.csv', 'rb') as f:  # note the 'b' flag--this is needed with CSV
    for row in csv.reader(f, delimiter=','):
        print row[2]