由于@Wooble在评论中指出,问题是您使用in
运算符来测试等同性而不是成员资格。
code = raw_input("Enter Code: ")
for line in open('test.txt', 'r'):
if code.upper() == line.split()[0].strip().upper():
print line
else:
print 'Not in file'
# this will print after every line, is that what you want?
也就是说,或许一个更好的主意(依赖于你的用例)就是将文件拖入字典并用它来代替。
def load(filename):
fileinfo = {}
with open(filename) as in_file:
for line in in_file:
key,value = map(str.strip, line.split())
if key in fileinfo:
# how do you want to handle duplicate keys?
else:
fileinfo[key] = value
return fileinfo
再经过加载这一切:
def pick(from_dict):
choice = raw_input("Pick a key: ")
return from_dict.get(choice, "Not in file")
而作为运行:
>>> data = load("test.txt")
>>> print(pick(data))
Pick a key: A
1234567
@juanchopanza我只是在做这:) –
OP:您的代码将当前未运行(你的引号不匹配)。请提供[MCVE(http://stackoverflow.com/help/mcve) –
嗯,你在使用'in',检查如果字符串'“A”'是在该行。为什么你会想到'“AB 2345678”'不具有'“A”'中呢?它就在那里。在开始时。提示:你可能想'.split()'和''==。 – geoffspear