Skip to content

Instantly share code, notes, and snippets.

@awdng

awdng/dirwalk.py

Last active Oct 26, 2017
Embed
What would you like to do?
The goal is to walk through all dirs and subdirs from a given path (as parameter) and show all subdirs and files recursively. For all files compute an md5 hash and show it. Catch exceptions.
import sys, os
import hashlib
color_white = '\033[0;0m'
color_green = '\033[0;32m'
base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
cli_path = sys.argv[1]
def dirwalk(base, relpath):
abspath = base + '/' + relpath
if abspath[-1:] != '/':
abspath += '/'
sys.stdout.write(color_green)
print('\n{}'.format(relpath))
sys.stdout.write(color_white)
try:
dirs = sorted(os.listdir(abspath))
for file in dirs:
if os.path.isdir(abspath + file):
dirwalk(base, '{}/{}'.format(relpath, file))
else:
hash = hashlib.md5(file.encode('utf-8')).hexdigest()
print('{:<55} {}'.format(file, hash))
except PermissionError:
print('Permission Error in {}'.format(abspath))
except:
print("Unexpected error:", sys.exc_info()[1])
if cli_path[0:1] == '/':
dirwalk('', cli_path)
else:
dirwalk(base_path, cli_path)
@awdng

This comment has been minimized.

Copy link
Owner Author

@awdng awdng commented Oct 26, 2017

it basically works, just some issues with ordering that are a bit hard to explain in text, maybe you can copy and paste it to see yourself

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment