-1

I have CSV File named as names.csv:

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

Trying to print only 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])

Gave me:

KeyError: 2

Thankyou

Proteeti Prova
  • 1,079
  • 4
  • 25
  • 49
Grass
  • 185
  • 2
  • 14

3 Answers3

1

As per your latest comment you want to print last name which are in second column(index 1)

If fieldnames are not present then you should not use DictReader as it will take whatever in first row as key

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
'''
Tanmay jain
  • 814
  • 6
  • 11
0

Indices start at 0! So to get the the second column you have to access row[1]

Michael K.
  • 2,392
  • 4
  • 22
  • 35
0

You can user the argument fieldnames to give columns key names, then print each column by the key name.

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

reference: https://docs.python.org/2/library/csv.html