ActiveState Code

Recipe 576716: Create SHA Hashes of a Directory


Walk through a Directory creating SHA Hashes of each file path

Python
1
2
3
4
5
6
7
8
9
import sha
import os
def createsha(directory):
    """Walk through a Directory creating Sha Hashes of each file path"""
    for root, dirs, files in os.walk(str(directory)):
        for name in files:
            filepath = os.path.join(root, name)
            value = sha.new(filepath).hexdigest()
            print value

Comments

  1. 1. At 1:16 a.m. on 13 apr 2009, David Moss said:

    This example is misleading. The comment in the function states that it takes checksums of each file, but the function itself only takes checksums of the file paths found in a directory not their contents.

    Here is a small modification that will also make the output compatible with 'sha1sum -c' :-

    filepath = os.path.join(root, name)
    value = sha.new(open(filepath, 'rb').read()).hexdigest()
    print value, '*%s' % filepath
    
  2. 2. At 12:47 a.m. on 30 oct 2009, Stephen Akiki said:

    I made a more robust version of the previous commenters code if anyone reading this is interested:

    http://akiscode.com/articles/sha-1directoryhash.shtml

Sign in to comment