Question

I'm using the hashlib func in a script I'm writing, and I can't get it to take the files I'm pointing it towards - its only returning the hash of a 0kb file d41d8cd98f00b204e9800998ecf8427e.

I'm calling it like so: fHash=md5Checksum(f) where f is a full path string of a file.

The md5Checksum func is a lift from here: http://www.joelverhagen.com/blog/2011/02/md5-hash-of-file-in-python/ and I've tested the 2nd example directly with an explicitly typed path to a file and it returns the correct hash.

I am also using the os.path.getsize method in the same way (fSize=os.path.getsize(f)) and that is picking the file up correctly.

When I dump the contents of the f string in my code, and compare it to the explicitly typed path, I notice it lacks ' markers around the string:

/home/.../(500) Days of Summer[2009]/11 - Regina Spektor - Hero.mp3 from a 'print f'

and from the explicitly typed path:

print 'The MD5 checksum of text.txt is', md5Checksum('/home/.../deduper/test.txt') (which works)

If I manually add ' markers to the path the code falls over:

IOError: [Errno 2] No such file or directory: "'/home/.../(500) Days of Summer[2009]/11 - Regina Spektor - Hero.mp3'"

This makes me suspect I'm not passing the path correctly. I'm on a ubuntu box if that matters.

EDIT

I'm a buffoon. I've been stuck on this for a few days, and its only through posting it on here and checking the indentations I've noticed I've messed one of them up on the md5Checker method along the way... I've fixed it, and this totally works. Thank you all for making me check.... (for the record, I had the m.update(data) line inline with the break. Thats not going to work now is it.... :s

def md5Checksum(filePath):
 fh = open(filePath, 'rb')
 m = hashlib.md5()
 # print "File being hashed: " + filePath
 while True:
  data = fh.read(8192)
  if not data:
   break
  m.update(data)
 return m.hexdigest()   
Was it helpful?

Solution

I had somehow got the indentation misalign, not enough to cause it to fall over and give me an error, but enough for it to not work. Answer is posted in the original question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top