【问题标题】:How to search txt file from python using while loop如何使用while循环从python中搜索txt文件
【发布时间】:2015-07-07 16:43:26
【问题描述】:

我有这个代码:

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,任何帮助将不胜感激。

【问题讨论】:

  • 好的,我以为是这样的,谢谢。基本上,如果书名不在 txt 文档中,我希望它能够重复问题,让用户再次有机会输入书名。
  • 在这种情况下,只需将整个内容放在由bool 变量保护的while 循环中,当您在循环中找到书名的实例时,设置变量以便退出循环。
  • 是的,它的间距为 4 倍,但它会通读每本书的标题印刷,直到遇到符合搜索的书为止
  • 没有while line in searchfile:这样的说法,虽然有While True: for line...

标签: python loops search for-loop while-loop


【解决方案1】:

假设您想不断重复搜索直到找到某些内容,您可以将搜索包含在一个由标志变量保护的 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

【讨论】:

    【解决方案2】:

    试试这个:

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

    您将内容加载到列表中并使用布尔标志来控制您是否已在文件中找到该书。当你找到它时,你就完成了,可以关闭文件了。

    【讨论】:

      猜你喜欢
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 2021-12-20
      • 2021-10-23
      • 2012-07-20
      相关资源
      最近更新 更多