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.
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
. ;)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.