Created
May 14, 2014 04:17
-
-
Save rosenhouse/01dfee20360599f000ac to your computer and use it in GitHub Desktop.
Python stream hasher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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