搜索文本文件并显示匹配的行

时间:2017-02-22 11:09:18

标签: python

在成功找到并打印文本文件中的行后,循环找不到第二个搜索短语。第二次提示用户输入搜索短语时,它不会找到它,而是打印"Please try again"

searchfile = open("Test.txt", "r")
content = searchfile.readlines()
lines = len(content)

while lines>0:
    phrase = raw_input('Please enter search word ')
    for line in content:
        if phrase in line:
            print (line)
            found = True

    else:
        print 'Please try again'
        break

searchfile.close()

1 个答案:

答案 0 :(得分:1)

从代码中删除break

phrase // word you are searching for...
with open("Test.txt") as f:
    for line in f:
        if phrase in line:
            print (line)

这将打印所有匹配的行。