ELSE Statement for CSV file not working

111 Views Asked by At

I'm trying to fit in an ELSE statement for a variable within a CSV File.

CSV File:

abcd, qwerty, aoo9
afjd, wijfs, aaaa
12as, 54as, oozz

I have attempted the following:

string1 = raw_input('User input: ')
with open('FILE.csv', "rb") as csvfile:
        z = csv.reader(csvfile, delimiter=',')
        for row in z:
            if string1 in row[1]: 
                print 'A' 
            else:
                print 'B'
                sys.exit()

However, regardless of whether the user's input is in row[1] or not, it will still print 'B'.

I expect that if the user inputs qwerty, wijfs, or 54as as string1 which all lie in row[1], it will print 'A', however if the user inputs something for string1 does is not in row[1], it will print 'B'

I have also tried:

elif variable not in row [1]: #...

But that doesn't work either.

Thanks.

2

There are 2 best solutions below

14
On

Clearly, either variable or row[1] does not contain what you think it contains. Add a print statement as follows:

    for row in z:
        print '<{}> ?= <{}>'.format(variable, row[1]) # add this line.
        if variable in row[1]: 

to see what's in those two variables (including leading or trailing white space). Most likely, they will not contain what you think they contain.

3
On

Your CSV file contains spaces. Your program will behave as expected if you input " querty" instead of "querty".

You can modify the CSV file or use the strip function to remove leading and trailing whitespace of row[1].

Or use the skipinitialspace parameter of the csv.reader. ;)