Skip to content Skip to sidebar Skip to footer

Python And Csv Reader: Failing To Print All The Rows In A Text File That Do Not Have A Field That Contains A Certain String

I have the following repl.it program, and cannot get one part of the program to work (the logic is wrong) The context is that of a dating site. in the 'matchmagic' subroutine, I wa

Solution 1:

If you add a header line to the CSV file when it is first created, you can use csv.DictReader to read the rows and use the column name to filter. This is nice because both your CSV and your code self document. So, just testing one column, your code could be:

import csv

def matchmagic():
    print("===Creating Match===")
    keystrength=input("Enter one of your key strengths:").upper()
    withopen("dating.txt","r") as f:
        reader=csv.DictReader(f)
        return [rowforrowin reader if row["keystrength"].upper()!=keystrength]

result= matchmagic()
for r inresult:
    print(r.values())

dating.txt

FName,LName,Username,password,Gender,email,dob,Religion,keystrength,contactcount
Joe,Bloggs,JoeBbird,open123,M,jblogs@gmail.com,10/10/20,Christian,patience,0
Darth,Vader,vader6599,open123,M,dvader@deathstar.com,10/10/20,Sith,impatience,0

This code is testing for exact matches. I added "impatience" to highlight that a test of whether "patience" is just somewhere in the string can be problematic.

Post a Comment for "Python And Csv Reader: Failing To Print All The Rows In A Text File That Do Not Have A Field That Contains A Certain String"