import os, hashlib, pickle

filelist = {}


def get_md5(file):
    with open(file, 'rb') as file_to_check:
        # read contents of the file
        data = file_to_check.read()
        # pipe contents of the file through
        md5_returned = str(hashlib.md5(data).hexdigest())
    return md5_returned


with open("dump.pickle", 'rb') as fp:
    filelist = pickle.load(fp)

for dirpath, dirs, files in os.walk(r"/var/www/html/wp-content/uploads"):
    for filename in files:
        try:
            value = filelist.get(get_md5(os.path.join(dirpath, filename)))
            if value and os.path.split(value)[1] != filename:
                print(value, os.path.join(os.path.split(value)[0], filename))
                os.rename(os.path.join(os.path.split(value)[0], filename),value)
        except (FileNotFoundError, UnicodeEncodeError):
            continue

