George Pascal
George Pascal

Reputation: 59

Python: Returning a filename for matching a specific condition

import sys, hashlib
import os

inputFile = 'C:\Users\User\Desktop\hashes.txt' 
sourceDir = 'C:\Users\User\Desktop\Test Directory' 

hashMatch = False
for root, dirs, files in os.walk(sourceDir):
    for filename in files:
    sourceDirHashes = hashlib.md5(filename) 
    for digest in inputFile: 
        if sourceDirHashes.hexdigest() == digest:
            hashMatch = True
            break
if hashMatch:
    print str(filename)
else:
    print 'hash not found'

Contents of inputFile =

2899ebdb5f7a90a216e97b3187851fc1
54c177418615a90a6424cb945f7a6aec
dd18bf3a8e0a2a3e53e2661c7fb53534

Contents of sourceDir files =

test
test 1
test 2

I almost have the code working, I'm just tripping up somewhere. My current code that I have posted always returns the else statement, that the hash hasn't been found, even although they do as I have verified this. I have provided the content of my sourceDir so that someone case try this, the file names are test, test 1 and test 2, the same content is in the files.

I must add however, I am not looking for the script to print the actual file content, but rather the name of the file.

Could anyone suggest to where I am going wrong and why it is saying the condition is false?

Upvotes: 0

Views: 656

Answers (1)

zorg93
zorg93

Reputation: 39

You need to open the inputFile using open(inputFile, 'rt') then you can read the hashes. Also when you do read the hashes make sure you strip them first to get rid of new line characters \n at the end of the lines

Upvotes: 1

Related Questions