Boto3/S3: Renaming an object using copy_object

PythonAmazon Web-ServicesAmazon S3Boto3

Python Problem Overview


I'm trying to rename a file in my s3 bucket using python boto3, I couldn't clearly understand the arguments. can someone help me here?

What I'm planing is to copy object to a new object, and then delete the actual object.

I found similar questions here, but I need a solution using boto3.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikAView Question on Stackoverflow
Solution 1 - PythonMikAView Answer on Stackoverflow
Solution 2 - PythonBoto UserView Answer on Stackoverflow
Solution 3 - PythonjpgardView Answer on Stackoverflow