检查字符串是否在文件中

时间:2017-12-20 00:12:55

标签: python-2.7

我有少量代码,我试图在哈希列表中检查哈希,并返回匹配或不匹配。现在,下面的代码是检查并打印每一行(在使用tkinter选择哈希文件之后)。如何将此减少为用户的单个输出?

输出示例(测试文件中有两个哈希示例):

HASH在数据库中找到了!

找不到哈希

我只希望显示一个结果,找到哈希值,或者找不到哈希值。

    user_hash = raw_input('What is the hash you would like to check?: ')
    toplevel = Tk()
    toplevel.withdraw()
    filename = tkFileDialog.askopenfilename()        
    with open(filename) as f:
        found=False
        for line in f:
            if user_hash in line:       
                print('HASH FOUND IN DATABASE!')
            else:
                print('Hash not found')

1 个答案:

答案 0 :(得分:0)

如果找到匹配的哈希值,那么就完成了,只需通过文件中的行突破循环:

for line in f:
    if user_hash in line:       
        print('HASH FOUND IN DATABASE!')
        break
    else:
        print('Hash not found')