从用户输入返回python中文本文件中的一行的项目

时间:2014-05-06 17:07:30

标签: python search return raw-input

code = raw_input("Enter Code: ')
for line in open('test.txt', 'r'):
    if code in line:
        print line
    else:
        print 'Not in file'

test.txt文件看起来像这样

A        1234567
AB       2345678
ABC      3456789
ABC1     4567890

输入为A时 打印行返回所有带有A而不是第一行的行。注意:test.txt文件大约有2000个条目。我只想返回用户现在输入的数字

1 个答案:

答案 0 :(得分:1)

正如@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