1. 程式人生 > >Python 修改目錄下所有檔名為MD5

Python 修改目錄下所有檔名為MD5

import os
import hashlib


def file_md5(file_name, block_size=2**20):
    if not os.path.isfile(file_name):
        return
    hash = hashlib.md5()
    with open(file_name, 'rb') as f:
        while True:
            b = f.read(block_size)
            if not b:
                break
            hash.update(b)
        return
hash.hexdigest() for root, dirs, files in os.walk("your_path"): for file in files: file_path = os.path.join(root, file) md5 = file_md5(file_path) print file_path, md5 if md5: os.rename(file_path, os.path.join(root, md5))