[英]ELSE Statement for CSV file not working
我正在尝试为CSV
文件中的变量添加ELSE
语句。
CSV 文件:
abcd, qwerty, aoo9 afjd, wijfs, aaaa 12as, 54as, oozz
我尝试了以下方法:
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()
但是,无论用户的输入是否在row[1]
,它仍然会打印 ' B
'。
我希望如果用户输入qwerty
、 wijfs
或54as
作为 string1 ,它们都位于row[1]
,它将打印“ A
”,但是如果用户输入 string1 的某些内容不在row[1]
,它将打印打印“ B
”
我也试过:
elif variable not in row [1]: #...
但这也行不通。
谢谢。
您的 CSV 文件包含空格。 如果您输入" querty"
而不是"querty"
您的程序将按预期运行。
您可以修改 CSV 文件或使用strip
函数删除row[1]
前导和尾随空格。
或者使用skipinitialspace
的参数csv.reader
。 ;)
显然, variable
或row[1]
不包含您认为它包含的内容。 添加打印语句如下:
for row in z:
print '<{}> ?= <{}>'.format(variable, row[1]) # add this line.
if variable in row[1]:
查看这两个变量中的内容(包括前导或尾随空格)。 最有可能的是,它们不会包含您认为它们包含的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.