2015-04-28 41 views
2

我有這樣的代碼:如何利用搜索從蟒蛇的txt文件,而循環

b = str(raw_input('please enter a book ')) 
searchfile = open("txt.txt", "r") 
for line in searchfile: 
    if b in line: 
     print line 
     break 
else: 
    print 'Please try again' 

這適用於我想做的事情,但我想,如果此行去重複循環,以改善它else聲明。我試圖通過一個while循環運行它,但它說'line' is not defined,任何幫助將不勝感激。

+0

[Python中的可能重複:逐行讀取文件中的行到數組](http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array) – Celeo

+0

好吧,我認爲這是這樣的,謝謝。基本上,如果該書的標題不在txt文檔中,我希望能夠重複該問題以給用戶另一個輸入書名的機會。 – toby

+0

在這種情況下,只需將全部內容放在由'bool'變量保護的'while'循環中,並且當您在循環中找到書名的實例時,請設置該變量以便退出循環。 – malfunctioning

回答

2

假設你要重複搜索持續,直到事情被發現,你可以附上由一個標誌變量守衛while循環中搜索:

with open("txt.txt") as searchfile: 
    found = False 
    while not found: 
     b=str(raw_input('please enter a book ')) 
     if b == '': 
      break # allow the search-loop to quit on no input 
     for line in searchfile: 
      if b in line: 
       print line 
       found = True 
       break 
     else: 
      print 'Please try again' 
      searchfile.seek(0) # reset file to the beginning for next search 
0

試試這個:

searchfile = open("txt.txt", "r") 
content = searchfile.readlines() 
found = False 

while not found: 
    b = raw_input('Please enter a book ') 
    for line in content: 
     if b in line: 
      print line 
      found = True 
      break 
    else: 
     print 'Please try again' 

searchfile.close() 

你加載一個列表的內容,並使用一個布爾標誌來控制,如果你已經發現了這本書的文件中。當你找到它時,你就完成了並可以關閉文件。