Skip to content

Instantly share code, notes, and snippets.

@ivansabik
Last active May 5, 2017 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivansabik/246e1f9e68ae8fa06ab3bf267ac1f36a to your computer and use it in GitHub Desktop.
Save ivansabik/246e1f9e68ae8fa06ab3bf267ac1f36a to your computer and use it in GitHub Desktop.
Compares md5 hashes for files in two directories recursively. It will compare using one dir as base (the left one) against the other one (the right one).
import argparse
import hashlib
import os
def get_checksum(f):
md5 = hashlib.md5()
md5.update(open(f).read())
return md5.hexdigest()
def compare_files_recursively(left_dir, right_dir, debug):
diff = {}
for (dirpath, dirnames, filenames) in os.walk(left_dir):
for filename in filenames:
left_filename = os.path.join(dirpath, filename)
left_file_md5 = get_checksum(left_filename)
right_filename = left_filename.replace(left_dir, right_dir)
try:
right_file_md5 = get_checksum(right_filename)
except IOError:
print 'File does not exist: ' + right_filename
diff[right_filename] = 'Missing right'
continue
if left_file_md5 != right_file_md5 or debug is True:
print '-----------------------------------'
print 'Left filename: ' + left_filename
print 'Right filename: ' + right_filename
print 'Left hash: ' + left_file_md5
print 'Right hash: ' + right_file_md5
print 'Hashes equal?: ' + left_file_md5 == right_file_md5
print 'Diff: {}'.format(diff)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=('Compare files in a folder (left) against files in other folder (right).'
'Kind of like left merging!'))
parser.add_argument('--left',
dest='left_dir',
help='Path to base directory used for the comparison',
default='./before')
parser.add_argument('--right',
dest='right_dir',
help='Path to directory to compare against',
default='./after')
parser.add_argument('-d', '--debug',
dest='debug', action='store_true',
help='Debug mode, print all comparisons, else only failed')
args = parser.parse_args()
compare_files_recursively(args.left_dir, args.right_dir, args.debug)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment