Skip to content

Instantly share code, notes, and snippets.

@fzembow
Created February 22, 2019 17:22
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 fzembow/ee4d15cecaa581e357ed33d72b5973f3 to your computer and use it in GitHub Desktop.
Save fzembow/ee4d15cecaa581e357ed33d72b5973f3 to your computer and use it in GitHub Desktop.
Script to add md5 hash to filename
"""
Given filenames, MD5 hashes them and puts the hash in the filename
"""
import glob
import hashlib
import os
import random
import sys
def hash_file(filename):
hasher = hashlib.md5()
with open(filename) as afile:
buf = afile.read()
hasher.update(buf)
return hasher.hexdigest()
def hash_pattern(filenames):
for filename in filenames:
file_hash = hash_file(filename)
(root, ext) = os.path.splitext(filename)
if file_hash in root:
continue
new_filename = root + file_hash + ext
os.rename(filename, new_filename)
print(root, file_hash, new_filename)
if __name__ == "__main__":
argv = sys.argv
if len(argv) == 1:
print("Must specify a file or a glob pattern")
sys.exit(1)
filenames = argv[1:]
hash_pattern(filenames)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment