如何把指定阿里云文件夹下的所有文件移动到另一个文件夹下,移动文件时把文件名称(不包括文件后缀)进行md5编码

发布于:2025-09-02 ⋅ 阅读:(17) ⋅ 点赞:(0)

如何把指定阿里云文件夹下的所有文件移动到另一个文件夹下,移动文件时把文件名称(不包括文件后缀)进行md5编码。
安装SDK:

bash
pip install oss2
编写Python脚本:

 # 认证信息
# 认证信息
auth = oss2.Auth('YOUR_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY_SECRET')
bucket_name = 'YOUR_BUCKET_NAME'
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com' # 替换为你的Region的Endpoint

    bucket = oss2.Bucket(auth, endpoint, bucket_name)


    # 源目录和目标目录
    source_prefix = 'house_mp4/'
    target_prefix = 'house/'
    print("=" * 60)
    print("开始安全的文件重命名和移动操作")
    print("=" * 60)
    
    processed_count = 0
    error_count = 0
    skipped_count = 0
    
    try:
        for obj in oss2.ObjectIterator(bucket, prefix=source_prefix):
            if obj.key == source_prefix:
                continue
                
            old_key = obj.key
            print(f"\n🔍 处理: {old_key}")
            
            old_name = old_key.split('/')[-1]
            
            if not old_name.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')):
                print("⏭️  跳过非视频文件")
                skipped_count += 1
                continue
            
            # URL解码
            decoded_name = urllib.parse.unquote(old_name)
            
            # 分离文件名和扩展名
            if '.' in decoded_name:
                file_base_name, file_extension = decoded_name.rsplit('.', 1)
            else:
                file_base_name, file_extension = decoded_name, ''
            
            # MD5编码
            md5_hash = hashlib.md5(file_base_name.encode('utf-8')).hexdigest()
            
            # 构建新文件名
            new_file_name = f"{md5_hash}.{file_extension}" if file_extension else md5_hash
            new_key = target_prefix + new_file_name
            
            # 检查目标是否存在
            if bucket.object_exists(new_key):
                print(f"⚠️  目标已存在,跳过: {new_file_name}")
                skipped_count += 1
                continue
            # print(f"✅ 成功: {old_name} -> {new_file_name}")
            # break
            
            # 执行操作
            try:
                print(f"📋 复制: {old_key} -> {new_key}")
                bucket.copy_object(bucket_name, old_key, new_key)
                
                print(f"🗑️  删除原文件: {old_key}")
                bucket.delete_object(old_key)
                
                print(f"✅ 成功: {old_name} -> {new_file_name}")
                processed_count += 1
                
                # 添加短暂延迟,避免API限制
                time.sleep(0.1)
                # break
                
            except Exception as e:
                print(f"❌ 操作失败: {e}")
                error_count += 1
                continue
                
    except Exception as e:
        print(f"💥 严重错误: {e}")
    
    # 输出统计信息
    print("\n" + "=" * 60)
    print("处理统计:")
    print(f"✅ 成功处理: {processed_count} 个文件")
    print(f"⚠️  跳过: {skipped_count} 个文件")
    print(f"❌ 错误: {error_count} 个文件")
    print("=" * 60)

网站公告

今日签到

点亮在社区的每一天
去签到