2014-05-06 28 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'中。 –

相關問題