Reputation: 921
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 !
Upvotes: 0
Views: 104
Reputation: 87124
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)
Upvotes: 1
Reputation: 28636
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, " !"
Upvotes: 0
Reputation: 5440
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!
Upvotes: 3