由於@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