Home > front end >  How to check if a string is in a csv header
How to check if a string is in a csv header

Time:08-24

I have this function:

def check_csv(final_word):
    with open("directory\\trap_words.csv", "r") as f:
        reader = csv.reader(f)
        for i in reader:
            str(i)

            if final_word in i:
                return True
            else:
                return False

To check if the parameter final_word is in a csv file But it does not return true even if the string is the same as one of the words in the csv file This is the csv file: enter image description here

CodePudding user response:

Your function loops through each line in the CSV file. On the first iteration (the first line) it checks if final_word in i: and then either returns back to the function caller true or false and then exits

I think the miss here is understanding that a return is the end of the logic, even inside a loop. Once a function returns, it stops processing.

So your code never gets past the first line of the csv. A fix is to get rid of the else and unindent return False to be outside of the loop and rerun

def check_csv(final_word):
    with open("directory\\trap_words.csv", "r") as f:
        reader = csv.reader(f)
        for i in reader:
            str(i)

            if final_word in i:
                return True
        #only return false if we didn't already return true    
        return False
  • Related