MD5 checksum for a file ?

Mike C. Fletcher mcfletch at rogers.com
Wed Jan 23 12:38:14 EST 2002


Here's the script I use for checking cd image (.iso) checksums:

import md5, sys, os, time

def compute( filename, chunk = 2**20 ):
     file = open( filename, 'rb' )
     try:
         check = md5.new()
         data = file.read( chunk )
         count = 1
         while data:
             check.update( data )
             data = file.read( chunk )
         return check.hexdigest()
     except:
         print 'stopped at', file.tell()

def save( sum, filename ):
     target = filename + '.md5'
     if (
         (not os.path.exists( target )) or
         ( string.strip(string.lower(raw_input( "Overwrite file %s? 
(y/n)>"%( target ) ))) in ('y','yes') )
     ):
         open( target, 'w').write( sum )


if __name__ == "__main__":
     import sys
     t = time.time()
     print 'checking file', sys.argv[1]
     value = compute( sys.argv[1] )
     t = time.time()-t
     print "time %s value %s"%( t, value)


The chunk size is really important in getting any sort of decent 
throughput.  2**20 was what I came up with as working well on my Athlon 
1GHz with 256MB of ram, but other machines will likely have different 
sweet spots.

Enjoy,
Mike


Barghest wrote:

> Hi,
> 
> Somebody have a sample script to make a md5 from a file or to check if the
> md5 is equal ??
> 
> Thanks

_______________________________________
   Mike C. Fletcher
   http://members.rogers.com/mcfletch/






More information about the Python-list mailing list