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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32501995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:41:32  来源:igfitidea点击:

Boto3/S3: Renaming an object using copy_object

pythonamazon-web-servicesamazon-s3boto3

提问by MikA

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?

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

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.

我在这里找到了类似的问题,但我需要使用 boto3 的解决方案。

采纳答案by MikA

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

回答by Boto User

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:

您不能在 S3 中重命名对象,因此正如您所指出的,您需要将其复制到一个新名称,然后删除旧名称:

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

回答by jpgard

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

以下示例来自更新的 Boto3 文档中的copy()方法,该方法也适用于 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')

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.

CopySource (dict) -- 源桶的名称,源对象的键名,源对象的可选版本ID。字典格式为:{'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}。请注意,VersionId 键是可选的,可以省略。