How to rename files in directory with its sha1 hash with python? -
i need rename files in directory hash python. i've done same thing using c#:
console.write("enter path"); string path = console.readline(); foreach (var in directory.getfiles(path)) { try { using (sha1managed sha1 = new sha1managed()) { filestream f = new filestream(i.tostring(), filemode.open); byte[] hash = sha1.computehash(f); string formatted = string.empty; foreach (byte b in hash) { formatted += b.tostring("x2"); } f.close(); file.move(i.tostring(), path+"//" + formatted); } } catch (exception ex) { console.writeline(i.tostring()); }
can me started i'd use in python accomplish same? i'll using ubuntu, if makes difference.
in python if want compute hash (md5, sha1) there hashlib
module. make operations on filesystem there os
module. in modules find: sha1
object hexdigest()
method , listdir()
, rename()
functions. example code:
import os import hashlib def sha1_file(fn): f = open(fn, 'rb') r = hashlib.sha1(f.read()).hexdigest() f.close() return r fn in os.listdir('.'): if fn.endswith('.sha'): hexh = sha1_file(fn) print('%s -> %s' % (fn, hexh)) os.rename(fn, hexh)
attention: sha1_file()
function read whole file @ once not work huge files. homework try improve such files (read file in parts , update hash parts).
of course if fn.endswith('.sha'):
used test purposes only.
Comments
Post a Comment