从python中的文件字典中搜索内容

时间:2018-04-24 11:28:36

标签: python python-3.x

我有文件(字典),我想从文件中搜索特定内容,如何编写查询?

def name_search():
    target = open("customers.txt",'r')
    name_search = input('Search >')
    for line in target:
        if name_search in line:
            print(f'{name_search} in record!')
        else:
            print('Not in record!')

上面的代码有效,但是,它会尝试多次打印此行,具体取决于我在文件中有多少行。假设该行不存在:

Not in record!
Not in record!
Not in record!
Not in record!

1 个答案:

答案 0 :(得分:0)

如果您说您不想多次打印,只读完整个文件一次,那么请执行以下操作:

def name_search():
    target = open("customers.txt",'r')
    name_search = input('Search >')
    found = False  # use this to remember if we found something
    for line in target:
        if name_search in line:
            print(f'{name_search} in record!')
            found = True  # remember we found it!
            break  # this kicks you out of the loop, so you stop searching after you find something
    if not found:
        print('Not in record!')  # only prints this if we didn't find anything

或者,在更少的代码行中,您可以在"找到"中使用return语句。案件。人们有理由避免在代码中使用多个返回点,但我在此处将其作为选项提供:

def name_search():
    target = open("customers.txt",'r')
    name_search = input('Search >')
    for line in target:
        if name_search in line:
            print(f'{name_search} in record!')
            return  # kicks us out of the function after we find something
    print('Not in record!')  # still only prints this if we didn't find anything