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

我试图在 s3 bucket 中使用 python boto3重命名一个文件,但我不能清楚地理解其中的参数。有人能帮帮我吗?

我计划的是将对象复制到一个新对象,然后删除实际的对象。

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

99234 次浏览

You cannot rename objects in S3, so as you indicated, you need to copy it to a new name and then deleted the old one:

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

I found another solution

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()

Following examples from updated Boto3 documentation for the copy() method, which also works with copy_object() and appears to be the required syntax now:

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')

Note from documentation linked above:

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.