Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and CSV: find a row and give column value

Tags:

python

csv

It consists in creating a function def(,) that searches for the name of the kid in the CSV file and gives his age.

The CSV file is structured as this:

Nicholas,12
Matthew,6
Lorna,12
Michael,8
Sebastian,8
Joseph,10
Ahmed,15 

while the code that I tried is this:

def fetchcolvalue(kids_agefile, kidname):

    import csv

    file = open(kids_agefile, 'r')
    ct = 0

    for row in csv.reader(file):
        while True:
            print(row[0])
            if row[ct] == kidname:
                break

The frustrating thing is that it doesn't give me any error, but an infinite loop: I think that's what I'm doing wrong.

So far, what I learnt from the book is only loops (while and for) and if-elif-else cycles, besides CSV and file basic manipulation operations, so I can't really figure out how can I solve the problem with only those tools.

Please notice that the function would have to work with a generic 2-columns CSV file and not only the kids' one.

like image 253
Francesco Anastasio Avatar asked Feb 05 '23 14:02

Francesco Anastasio


1 Answers

the while True in your loop is going to make you loop forever (no variables are changed within the loop). Just remove it:

for row in csv.reader(file):
    if row[ct] == kidname:
        break
else:
   print("{} not found".format(kidname))

the csv file is iterated upon, and as soon as row[ct] equals kidname it breaks.

I would add an else statement so you know if the file has been completely scanned without finding the kid's name (just to expose some little-known usage of else after a for loop: if no break encountered, goes into else branch.)

EDIT: you could do it in one line using any and a generator comprehension:

any(kidname == row[ct] for row in csv.reader(file))

will return True if any first cell matches, probably faster too.

like image 125
Jean-François Fabre Avatar answered Feb 08 '23 16:02

Jean-François Fabre