Python: Hashing files

Wednesday 6. February, 2008


Once again I decided I needed to make some md5sums for files, “Pythonic”-way. I have done it before, but I didn’t quite remember it, so some Googling gave the instructions, I write them down here, in case I’ll need it again

import hashlib
md5sum = hashlib.md5(open('tehfile','rb').read()).hexdigest()
sha1sum = hashlib.sha1(open('tehfile','rb').read()).hexdigest()

(I since sha1sum is longer, I decided to go with it instead of md5)

Basically the code above imports the hashlib-module and then generates md5 and sha1 sums in hexadecimal presentation for ‘tehfile’ opened in for reading in binary mode.


One Response to “Python: Hashing files”

  1. BigBrother Says:

    Admittedly, this will work but won’t close those files after we are ready (Garbage collector will close them eventually but that is usually when the execution of the script ends). It /might/ be better to do something like this:

    f1 = open(‘thefile’, ‘rb’)
    md5sum = hashlib.md5(

    This way you won’t end up with thousands of open files for sure.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: