如何把指定阿里云文件夹下的所有文件移动到另一个文件夹下,移动文件时把文件名称(不包括文件后缀)进行md5编码
如何把指定阿里云文件夹下的所有文件移动到另一个文件夹下,移动文件时把文件名称(不包括文件后缀)进行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的Endpointbucket = oss2.Bucket(auth, endpoint, bucket_name)# 源目录和目标目录source_prefix = 'house_mp4/'target_prefix = 'house/'print("=" * 60)print("开始安全的文件重命名和移动操作")print("=" * 60)processed_count = 0error_count = 0skipped_count = 0try:for obj in oss2.ObjectIterator(bucket, prefix=source_prefix):if obj.key == source_prefix:continueold_key = obj.keyprint(f"\n🔍 处理: {old_key}")old_name = old_key.split('/')[-1]if not old_name.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')):print("⏭️ 跳过非视频文件")skipped_count += 1continue# 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_hashnew_key = target_prefix + new_file_name# 检查目标是否存在if bucket.object_exists(new_key):print(f"⚠️ 目标已存在,跳过: {new_file_name}")skipped_count += 1continue# 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)# breakexcept Exception as e:print(f"❌ 操作失败: {e}")error_count += 1continueexcept Exception as e:print(f"💥 严重错误: {e}")# 输出统计信息print("\n" + "=" * 60)print("处理统计:")print(f"✅ 成功处理: {processed_count} 个文件")print(f"⚠️ 跳过: {skipped_count} 个文件")print(f"❌ 错误: {error_count} 个文件")print("=" * 60)