Mohit Sharma Mohit Sharma - 11 months ago 43
Python Question

How to find row number of a particular value with known column number in csv file through python

I am working on a problem to create a function find_row with three input parameters - file name, col_number and value. I want output like in given example:

For example, if we have a file a.csv:

1, 1.1, 1.2
2, 2.1, 2.2
4, 4.1, 4.2


print(find_row('a.csv', 0, 4)) would print 3,

print(find_row('a.csv', 2, 2.2)) would print 1, and

print(find_row('a.csv', 0, 100)) would print None.

The code I tried is :

import csv

def find_row(filename,col_number,value):
var = str(value)
coln = str(col_number)
o = open(filename, 'r')
myData = csv.reader(o)
index = 0
for row in myData:
if row[col_number] == var:
return index
else :

print find_row('a.csv',2,2.2)

It is throwing error :

File "C:/Users/ROHIT SHARMA/Desktop/", line 17, in find_row
if row[col_number] == var:

IndexError: list index out of range

I understand the error now, but not able to improve the code. Any help here guys??!



In your CSV file, the 3rd row has only one column, so 2 is not a valid index.

As an aside, it's cleaner to do

 for index, row in enumerate(myData):
    if row[col_number] == var:
        return index

Edit: Also, that CSV is going to give you problems. It can't find '2.2' because it actually returns ' 2.2'. Strip the spaces when you read or make sure the CSV is saved the "correct" way (no spaces between comma and content).

Edit2: If you MUST have a CSV with unequal rows, this will do the trick:

for index, row in enumerate(myData):
        if row[col_number] == var:
            return index
    except IndexError: