Skip to content

Instantly share code, notes, and snippets.

@hattorix
Created May 26, 2012 07:21
Show Gist options
  • Save hattorix/2792734 to your computer and use it in GitHub Desktop.
Save hattorix/2792734 to your computer and use it in GitHub Desktop.
rename file to SHA1
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
import hashlib
import gio
def get_hash_of_sha1(fname):
sha1 = hashlib.sha1()
f = open(fname, 'rb')
try:
sha1.update(f.read())
finally:
f.close()
return sha1.hexdigest()
def rename_file(fname):
hashval = get_hash_of_sha1(fname)
root, ext = os.path.splitext(fname)
root = os.path.dirname(root)
toname = '{0}{1}{2}'.format(root, hashval[0:8], ext)
if fname == toname:
print('pass: "{0}" is same name.'.format(fname))
elif os.path.exists(toname):
print('"{0}" is exists: go trash'.format(fname))
obj = gio.File(fname)
obj.trash()
else:
print('rename: {0} => {1}'.format(fname, toname))
os.rename(fname, toname)
if __name__ == "__main__":
for fname in sys.argv[1:]:
try:
rename_file(fname)
except IOError as e:
print '{0} => {1}'.format(fname, e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment