Created
June 23, 2013 19:34
-
-
Save juusimaa/5846242 to your computer and use it in GitHub Desktop.
Python (3.x) function to calculate MD5 checksum for given file.
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 calculateMD5(filename, block_size=2**20): | |
"""Returns MD% checksum for given file. | |
""" | |
import hashlib | |
md5 = hashlib.md5() | |
try: | |
file = open(filename, 'rb') | |
while True: | |
data = file.read(block_size) | |
if not data: | |
break | |
md5.update(data) | |
except IOError: | |
print('File \'' + filename + '\' not found!') | |
return None | |
except: | |
return None | |
return md5.hexdigest |
I needed to return the actual hash value, so modified return value to:
return md5.hexdigest()
import hashlib
from functools import partial
def md5sum(filename):
with open(filename, mode='rb') as f:
d = hashlib.md5()
for buf in iter(partial(f.read, 128), b''):
d.update(buf)
return d.hexdigest()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you should close your file as well or use the 'with' statement :)