0

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

5
  • what is inside i? Commented Aug 23, 2022 at 15:42
  • 2
    you're returning on first iteration of the loop. Perhaps, you need to move return False out of the loop Commented Aug 23, 2022 at 15:42
  • just words, no sentences or anything like that when i run a loop to print the items in this csv i get ['word1'], ['word2']...etc so im thinking that is somehow the problem Commented Aug 23, 2022 at 15:43
  • yes its the else statement that is messing it up, thank you, if you want you can post this as the answer and ill check mark it Commented Aug 23, 2022 at 15:45
  • The title says you only want to check the CSV header, which is the first row with all the field names. If that's really what you want, this code should work. Commented Aug 23, 2022 at 16:03

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.