user5147001
user5147001

Reputation:

Python3: search csv file for string and return row and column

I have a large csv file, and I am trying to search it for a string. and return the row and column. The code that I have so far will always return 'nope' for anything that I enter.

The code that I have so far:

def search_cell(string):
    with open('aanmaningen.chr', 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            if string in row:
                print(row[0])
                return row[0]
            else:
                print('nope')
                return 'nope'

For example:

When the csv file contains the string 'vve' in row 20, column 9, I want to be able to enter the string 'vve' and get the row and column number back.

Note: because the way the program i'm using exports data, it saves as a character seperated file (.chr), using the seperator and delimiter ';' essentially a .csv file with a non-standard seperator and delimiter

Upvotes: 1

Views: 5977

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 91007

Since you say -

I have a large csv file, and I am trying to search it for a string. and return the row and column.

That makes me believe that the expected string can be inside a particular column (as a substring) . If so, then what you are doing is wrong.

When you do -

for row in reader:

row is a list of all columns in that particular row. Then when you do -

if string in row:

It checks if the string is completely equal to any column in that row. Instead iterate over the row's columns and check if string is in any of the columns and return the row number and column number as a tuple. Use enumerate function to get index as well as the value for that index together.

Also, you return nope in the first row itself, if the string is not found there, you should only return nope after the complete for loop has ended, in which case you didn't find any match.

Example -

def search_cell(string):
    with open('aanmaningen.chr', 'r') as f:
        reader = csv.reader(f)
        for i, row in enumerate(reader):
            for j, column in enumerate(row):
                if string in column:
                    print((i,j))
                    return (i,j)
    print('nope')
    return 'nope'

This will return the 0 indexed row and column number where the string was first found , or nope if it was not found.

Upvotes: 2

Related Questions