Source

woocode / py / slice_path.py

# -*- encoding:utf-8 -*-
import sys
import os
from hashlib import sha1

def mkdir(p):
    if not os.path.exists(p):
        print 'mkdir', p

        os.makedirs(p)

def slice(li, step):
    num = len(li)
    _li = range(0, num, step)

    for index, elem in enumerate(_li):
        if index == (len(_li) - 1):
            end = None
        else:
            end = _li[index + 1]
        yield li[elem:end]

def hash(s):
    hx = sha1(s).hexdigest()
    return (hx[0:2], hx[2:4])

def main():
    path = sys.argv[1]
    dest = os.path.dirname(path)

    for root, dirs, files in os.walk(path):
        for fn in files:
            new_path = '/'.join(hash(fn))
            fp = os.path.join(root, fn)
            new_fp = os.path.join(dest, new_path, fn)
            mkdir(os.path.dirname(new_fp))
            print 'mv %s -> %s' % (fp, new_fp)
            os.rename(fp, new_fp)

if __name__ == '__main__':
    main()