# Find csv item index

I'm quite new to Python and I have been trying to find a way to search a csv for a test string and return the index of that item in the csv. I am using the code below but find it hard to believe that there is not a function built in to the csv module to do this. I want to perform the 'lookup' so that I can select the column index, I will then do the same for another value and use the row index to get the data from the cell at the intersection of both indices. What I have at the moment returns for example '[4]7' when printed.

    with open('rooms.csv','r') as inf, open('roms_out.csv','w') as outf:
writer = csv.writer(outf, quoting=csv.QUOTE_MINIMAL)
m = [i for i, elem in enumerate(row) if MyApp.group_1 in elem]
if m:


There are any number of ways to accomplish this kind of thing in Python. Here's one:

from string import ascii_uppercase
with open('Coding_ID.csv','r') as inf, open('roms_out.csv','w') as outf:
writer = csv.writer(outf, quoting=csv.QUOTE_MINIMAL, lineterminator = '\n')
try:
except:
next

10, 6


Note, that the index within the row (column number) needs to be incremented to get an Excel style column number. Of course, there's no need to do that, if you're comfortable with zero-based indexing. Also, the str() function is not required.

To get Excel row/column designation (up to 'Z', but it could be fixed to give more columns--e.g. "AP", "ZZ", etc.) substitute the following for the print statement, above:

print('{}, {}'.format(ascii_uppercase[row.index(group_1)], reader.line_num))


This will print J, 6

As an additional (possible) benefit, this code will print the indices of every occurrence of the desired item. The lineterminator parameter in the csv.writer call is needed to eliminate extra newlines.

• Here is some good coverage of the csv module: link – Edward Carney Mar 7 '16 at 21:37
• Your first example is perfect for my needs, it produces print output eg. '7, 2' and gives 1, 1 as Excel's A:1 so isn't quite zero based but I can take the '+ 1' out and add a '-1' to the line number if I need to. The alternative line of code doesn't appear to give any output at all, that's just a comment as the fist version is what i was looking for. – Stevo Mar 7 '16 at 22:16
• If this line is missing, you won't see anything in the second case: from string import ascii_uppercase – Edward Carney Mar 7 '16 at 22:28
• Also, Stevo, have a look at this link. Thanks. :-) – Edward Carney Mar 7 '16 at 22:31
• Its in there and there are no don't appear to be any warnings or objections... just no output.. Im using Python 2.7 could that make any difference ? – Stevo Mar 7 '16 at 22:34