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

项目以从用户输入返回python文本文件中的一行,python,search,return,raw-input,Python,Search,Return,Raw Input,test.txt文件如下所示 code = raw_input("Enter Code: ') for line in open('test.txt', 'r'): if code in line: print line else: print 'Not in file' 当输入为 打印行返回所有带有A的行,而不仅仅是第一行。注意:test.txt文件大约有2000个条目。我只想返回一行,其中包含用户目前输入的数字。正如@Wooble在评论中指出

test.txt文件如下所示

code = raw_input("Enter Code: ')
for line in open('test.txt', 'r'):
    if code in line:
        print line
    else:
        print 'Not in file'
当输入为
打印行返回所有带有A的行,而不仅仅是第一行。注意:test.txt文件大约有2000个条目。我只想返回一行,其中包含用户目前输入的数字。

正如@Wooble在评论中指出的,问题在于您使用
in
操作符来测试等价性,而不是成员资格

A        1234567
AB       2345678
ABC      3456789
ABC1     4567890
也就是说,可能更好的办法(取决于您的用例)是将该文件拉入字典并使用它

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")

@juanchopanza我只是这么做:)OP:您的代码当前无法运行(您的引号不匹配)。请提供一口井,您正在使用
中的
,它检查字符串
“a”
是否在该行中。为什么您希望
“AB 2345678”
中没有
“A”
?就在那里。一开始。提示:您可能需要
.split()
=
。OP:您试图编辑我的帖子,而不是写评论:)。要获取整数形式的值,只需对其调用
int
(例如在
def pick
do
return from_dict.get(int(选项),“Not in file”)
很抱歉,我是第一次来到这里。对python来说是非常陌生的。在运行脚本时,它会返回A的值,但下一行也是这样。内存问题?@user3609157
value=int(pick(data))
将值作为int存储在变量
value
中。
>>> data = load("test.txt")
>>> print(pick(data))
Pick a key: A
1234567