Skip to content

Instantly share code, notes, and snippets.

@rosenhouse
Created May 14, 2014 04:17
Show Gist options
  • Save rosenhouse/01dfee20360599f000ac to your computer and use it in GitHub Desktop.
Save rosenhouse/01dfee20360599f000ac to your computer and use it in GitHub Desktop.
Python stream hasher
def local_file_hash(filepath):
'''
Return a hash of the file's contents, if file exists
Otherwise return None
'''
hasher = hashlib.sha256()
blocksize=(1 << 16)
try:
with open(filepath, "rb") as afile:
buf = afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.digest().encode('hex')
except IOError as exception:
if exception.errno == errno.ENOENT: # file doesn't exist
return None
else:
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment