2014-05-06 23 views
-2
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文件看起来像这样项目在文本文件中的Python从用户输入返回行

A  1234567 
AB  2345678 
ABC  3456789 
ABC1  4567890 

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

+1

@juanchopanza我只是在做这:) –

+0

OP:您的代码将当前未运行(你的引号不匹配)。请提供[MCVE(http://stackoverflow.com/help/mcve) –

+1

嗯,你在使用'in',检查如果字符串'“A”'是在该行。为什么你会想到'“AB 2345678”'不具有'“A”'中呢?它就在那里。在开始时。提示:你可能想'.split()'和''==。 – geoffspear

回答

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 
+0

OP:您试图编辑自己的帖子,而不是写评论:)的。为了得到值作为一个整数,只是调用'int'他们(例如,在'高清pick'做'回报from_dict.get(INT(选择),“没有文件”)' –

+0

对不起,我在这里是第一次。和非常新的蟒。当运行脚本它返回A的值但是下面也对下一行。<在0x02414970功能拾取>存储器的问题? – user3609157

+0

@ user3609157'值= INT(挑(数据))'将将值作为int存储在变量'value'中。 –

相关问题