PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 26, 2022

[FIXED] How to check if a string is in a csv header

 August 26, 2022     csv, python     No comments   

Issue

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


Solution

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


Answered By - JNevill
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing