你怎么让python继续阅读行,直到满足条件?

时间:2016-06-30 16:16:28

标签: python

这是我目前的代码:

StockSearch = input("Search For Product (Name Or Code):\n")
with io.open('/home/jake/Projects/Stock','r', encoding='utf8') as f:
    for line in f:
        Read = f.readline()
        while Read!='':
            if StockSearch == Read:      
                print (Read)

我正在尝试让python继续读取文件的每一行,直到没有任何一行,并将用户的输入与其中一行匹配,如果没有,它将打印错误代码。

提前谢谢。

3 个答案:

答案 0 :(得分:1)

StockSearch = input("Search For Product (Name Or Code):\n")
found = False
with io.open('/home/jake/Projects/Stock','r', encoding='utf8') as f:
    for line in f:
        line = line.rstrip('\n')
        if StockSearch == line:      
            print(line)
            found = True
            break
if not found:
    print("Nothing found")

答案 1 :(得分:1)

这看起来类似于我在Raymond Hettinger的'Pythonic' coding video上看到的模式。它被称为iterating with a sentinel value

格式如下:

with open('filename.txt') as f:
    blocks = []
    read_block = partial(f.read, 32)
    for block in iter(read_block, ''):
        blocks.append(block)

在您的情况下,您可以用停止值替换''

答案 2 :(得分:0)

您可以遍历打开的文件来逐行读取。如果满足条件,则break退出循环。在循环结束时添加else语句,以打印错误消息。只有在读取整个文件且未找到匹配项时,才会执行else块。

search_text = input("Search For Product (Name Or Code):\n")
with io.open('/home/jake/Projects/Stock','r', encoding='utf8') as f:
    for line in f:
        if search_text == line.strip():
            print line
            break
    else:
        print 'Search text not found'