0

I have a small amount of code in which I am trying to check a hash against a hash list, and return a match or no match. Right now the code below is checking and printing each line (after using tkinter to select the hash file). How can I reduce this to a single output for the user?

Example of output (with two hash examples in the test file):

HASH FOUND IN DATABASE!

Hash not found

I only want ONE result to be displayed, either hash found, or no hash found.

    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')
deuer
  • 3
  • 5
  • If there is more than one entry in the file that passes, which one do you want to return, or does it matter? – paisanco Dec 20 '17 at 00:19
  • If True, as in hash found, print "Hash Found" only once. If not Found, print "hash not found" only once. Right now, its displaying for each line in the list, which on a hash file is not realistic. – deuer Dec 20 '17 at 00:42

1 Answers1

0

If as soon as a matching hash is found, you are done, simply break out of the loop through lines in the file:

for line in f:
    if user_hash in line:       
        print('HASH FOUND IN DATABASE!')
        break
    else:
        print('Hash not found')
paisanco
  • 4,098
  • 6
  • 27
  • 33
  • It does stop the process, but isn't really the best if the matching hash is thousands of lines down. Is there a way to hide the display prior to the "find and break" – deuer Dec 20 '17 at 00:55
  • If memory usage is your concern, see https://stackoverflow.com/questions/4940032/how-to-search-for-a-string-in-text-files for a trick using mmap. If freezing the display during the search is your concern, the search could be done in a separate thread from the display perhaps. – paisanco Dec 20 '17 at 01:12
  • Nope just want the code to display efficiently for the user, if the hash is in the file, say it. If not say it. Either response in one line. Maybe I need tro read the entire file into the buffer and check the buffer. – deuer Dec 20 '17 at 01:17
  • It really depends how large the file is. You could read it into one big string and search the string for the user_hash, etc if the file is not too large. – paisanco Dec 20 '17 at 01:20