如何使用while循环从python中搜索txt文件

时间:2015-04-28 17:28:47

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

我有这段代码:

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,任何帮助都将受到赞赏。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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()

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