2016-03-10 82 views
0
elif controlpanel == "B": 
print("Please input numberplate below") 
inputting = input() 
lookup = inputting 
with open('numberplates.txt') as myFile: 
    for num, line in enumerate(myFile, 1): 
     if lookup in line: 
      print("found at line:", myFile.readline()) 

這裏,我的代碼應該查看名爲'numberplates.txt'的.txt文件,但它並不總是工作。在文本文件中搜索一個字符串,然後打印該行(不按預期方式工作)

Numberplate: JK76FBG Speed: 493 
Numberplate: UH67KCH Speed: 1063 
Numberplate: AI78DHC Speed: 1063 
Numberplate: AL08HCD Speed: 173 
Numberplate: JH78SCD Speed: 206 
Numberplate: HJ78LBC Speed: 583 

這是.txt文件的內容。

這是,如果我輸入JK76FBG

Please input numberplate below JK76FBG found at line: Numberplate: 
UH67KCH Speed: 1063 

但是,如果我輸入AL08HCD,我得到一個錯誤會發生什麼。

Please input numberplate below 
AL08HCD 
Traceback (most recent call last): 
    File "file path", line 43, in <module> 
    with open('numberplates.txt') as myFile: 
IOError: [Errno 2] No such file or directory: 'numberplates.txt' 

它似乎要麼給我一個錯誤,要麼打印字符串下面的行。

在此先感謝

回答

0
print("found at line:", myFile.readline()) 

你爲什麼要使用的ReadLine()再次,只是打印行

print("found at line:", line) 
+0

謝謝!它工作得很好 – Bocui

相關問題