0

I'm trying to parse a CSV file like which is like this :

name, init
Tim Keller, TK
Nick Fill, NK

And here's what I want, somebody enter like TK and I will give him back Hello Tim Keller !

The only issue I have is I can't fallback in my CSV file (Well.. I don't know how to do it..)

Here's what I made :

with open('datas.csv', 'rb') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
        for row in spamreader:
                for columns in row:
                        if columns == args[i]:
                                print "Hello ", columns, " !"

Well with that code if the user enter TK I will print back Hello TK !

I tried something like columns-1 but seems not to be like it..

Thanks for any help !

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
nookonee
  • 871
  • 2
  • 8
  • 19

3 Answers3

3
            for columns in row:

is not necessary. If you do for row in spamreader, you already have both parts, just index row: row[0] is the name, row[1] is the nickname.

See the fine manual!

jcoppens
  • 5,306
  • 6
  • 27
  • 47
1

Based on your sample data your separator is a comma (,), or possibly a comma followed by a space. It's not clear what the quote char is, but I'd leave it as the default.

Also, I assume that the CSV file contains multiple lines like this:

name,init
Tim Keller,TK
Nick Fill,NK

The code to process this file would be like this:

import csv

search_initials = raw_input('Enter initials: ').strip()
with open('datas.csv', 'rb') as csvfile:
    for name, initials in csv.reader(csvfile):
        if initials == search_initials:
            print "Hello {}!".format(name)
mhawke
  • 84,695
  • 9
  • 117
  • 138
0

It would probably be clearer to not put the row into a "row" variable but into two more meaningful variables:

for name, init in spamreader:
    if init == args[i]:
        print "Hello ", name, " !"
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107