仅打印第二行

时间:2018-09-01 13:08:27

标签: python python-3.x csv selenium

我有 CSV文件,名为 names.csv

F_Name | L_Name
Sashi  | Thakur
Rup    | Chand
Nirmal | Kumar

仅尝试打印L_Name

import csv
with open('names.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        #print(row['first_name'], row['last_name'])
        print(row[1])

给我

  

KeyError:2

谢谢

3 个答案:

答案 0 :(得分:0)

索引从0开始!因此,要获取第二列,您必须访问row[1]

答案 1 :(得分:0)

根据您的最新评论,您要打印第二列(索引1)中的姓氏

如果不存在字段名,则不应使用DictReader,因为它将以第一行中的任何内容为键

import csv
with open('cs.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
    print(row[1])


#--------------------------------------------------
# fieldnames are present

import csv
with open('cs.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    #print(reader.fieldnames) 
    look_for = reader.fieldnames[1] #since L_name is at index 1
    for row in reader:
        print(row[look_for])

'''
csv file contents
F_Name,L_Name
Sherlock,Holmes
Bruce,Wayne

OrderedDict([('F_Name', 'Sherlock'), ('L_Name', 'Holmes')])
Holmes
OrderedDict([('F_Name', 'Bruce'), ('L_Name', 'Wayne')])
Wayne

['F_Name', 'L_Name']
Holmes
Wayne
'''

答案 2 :(得分:0)

您可以使用参数fieldnames为列指定键名称,然后按键名称打印每一列。

import csv with open('names.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames=['fname', 'lname'])
    for row in reader:
        print(row['lname'])

参考:https://docs.python.org/2/library/csv.html