用MD5值修改文件名

import os
import shutil
import hashlib
 
def calculate_md5(file_path):
    """计算文件的 MD5 值"""
    md5_hash = hashlib.md5()
    with open(file_path, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b""):
            md5_hash.update(chunk)
    return md5_hash.hexdigest()
 
def resolve_conflict(file_path):
    """解决文件名冲突,生成唯一文件名"""
    counter = 1
    base, ext = os.path.splitext(file_path)
    new_file_path = file_path
 
    # 如果文件名冲突,添加数字后缀
    while os.path.exists(new_file_path):
        new_file_path = f"{base}_{counter}{ext}"
        counter += 1
 
    return new_file_path
 
def organize_files_with_structure(root_folder, modified_root, log_txt):
    """重命名文件,保持原始文件目录结构"""
    with open(log_txt, 'w', encoding='utf-8') as log_file:
        for dirpath, _, filenames in os.walk(root_folder):
            for filename in filenames:
                old_file_path = os.path.join(dirpath, filename)
 
                if os.path.isfile(old_file_path):
                    # 计算 MD5 值并生成新文件路径
                    md5_name = calculate_md5(old_file_path)
                    extension = os.path.splitext(filename)[1]
                    # 创建与原始目录结构相同的路径
                    relative_path = os.path.relpath(dirpath, root_folder)
                    new_dir = os.path.join(modified_root, relative_path)
                    os.makedirs(new_dir, exist_ok=True)
                    new_file_path = os.path.join(new_dir, md5_name + extension)
 
                    # 解决文件名冲突
                    new_file_path = resolve_conflict(new_file_path)
 
                    # 复制文件到新路径
                    shutil.copy(old_file_path, new_file_path)
 
                    # 写入日志
                    log_file.write(f"{old_file_path} -> {new_file_path}\n")
                    print(f"处理文件: {old_file_path} -> {new_file_path}")
 
if __name__ == "__main__":
    # 指定原始文件夹路径
    folder_path = r"D:\T1"
    # 指定修改后文件夹根目录(可以单独设置)
    modified_root = r"D:\T1_modified"
    # 指定日志文件路径
    log_file = os.path.join(modified_root, "file_log.txt")
 
    if os.path.exists(folder_path):
        organize_files_with_structure(folder_path, modified_root, log_file)
        print(f"处理完成!日志已保存到 {log_file}")
        print(f"修改后文件存放在: {modified_root}")
    else:
        print("指定的文件夹不存在,请检查路径。")