Welcome, guest | Sign In | My Account | Store | Cart

Walk through a Directory creating SHA Hashes of each file path

Python, 9 lines
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

2 comments

David Moss 15 years ago  # | flag

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
Stephen Akiki 14 years, 5 months ago  # | flag

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

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

Created by andrew.canit on Sun, 12 Apr 2009 (MIT)
Python recipes (4591)
andrew.canit's recipes (2)

Required Modules

Other Information and Tasks