Boto3/S3:使用 copy_object 重命名对象

Boto3/S3: Renaming an object using copy_object

我正在尝试使用 python boto3 重命名我的 s3 存储桶中的文件,我无法清楚地理解参数。有人可以帮我吗?

我打算将对象复制到新对象,然后删除实际对象。

我在这里发现了类似的问题,但我需要一个使用 boto3 的解决方案。

S3中的对象无法重命名,所以如您所说,您需要将其复制为一个新名称,然后删除旧名称:

client.copy_object(Bucket="BucketName", CopySource="BucketName/OriginalName", Key="NewName")
client.delete_object(Bucket="BucketName", Key="OriginalName")

我找到了另一个解决方案

s3 = boto3.resource('s3')
s3.Object('my_bucket','new_file_key').copy_from(CopySource='my_bucket/old_file_key')
s3.Object('my_bucket','old_file_key').delete()

以下示例来自 copy() 方法的更新 Boto3 文档,该方法也适用于 copy_object() 并且现在似乎是必需的语法:

copy_source = {'Bucket': 'source__bucket', 'Key': 'my_folder/my_file'}
s3.copy_object(CopySource = copy_source, Bucket = 'dest_bucket', Key = 'new_folder/my_file')
s3.delete_object(Bucket = 'source_bucket', Key = 'my_folder/my_file')

上面链接的文档中的注释:

CopySource (dict) -- The name of the source bucket, key name of the source object, and optional version ID of the source object. The dictionary format is: {'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}. Note that the VersionId key is optional and may be omitted.