Skip to content

Instantly share code, notes, and snippets.

@juusimaa
Created June 23, 2013 19:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save juusimaa/5846242 to your computer and use it in GitHub Desktop.
Save juusimaa/5846242 to your computer and use it in GitHub Desktop.
Python (3.x) function to calculate MD5 checksum for given file.
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
@ChuckMoe
Copy link

you should close your file as well or use the 'with' statement :)

@jenreidschram-smarsh
Copy link

I needed to return the actual hash value, so modified return value to:

return md5.hexdigest()

@broderix
Copy link

broderix commented Mar 21, 2022

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