Amazon S3 boto:如何在存储桶中重命名文件?

74

如何使用boto在S3存储桶中重命名键?


1
投票重新开放,这是一个相当简单并且不太模糊的问题。我将编辑以明确提到文件代表s3密钥。 - David
1
如果有人想知道,您可以通过AWS Web界面完成此操作(右键单击文件->重命名)。 - scrowler
4个回答

70

在Amazon S3中,您无法重命名文件。您可以使用新名称将其复制,然后删除原始文件,但没有适当的重命名功能。


10
请注意,复制功能似乎是即时的(可能是符号链接)。因此,在执行此操作时速度不会有问题。 - Mauvis Ledford
18
在发表这条评论的时候,它似乎并不是即时的。我正在复制一个2GB的文件,需要几分钟的时间。 - dtbarne
  1. 有人能告诉我,将一个3GB的文件复制粘贴到同一存储桶和位置需要多长时间,然后删除原始文件?
  2. 用户界面似乎具有重命名功能。但是用户界面在后台是否也以相同的方式(复制和删除)工作?
- Yogesh Yadav

39

这里是一个使用Boto 2复制S3对象的Python函数示例:

import boto

def copy_object(src_bucket_name,
                src_key_name,
                dst_bucket_name,
                dst_key_name,
                metadata=None,
                preserve_acl=True):
    """
    Copy an existing object to another location.

    src_bucket_name   Bucket containing the existing object.
    src_key_name      Name of the existing object.
    dst_bucket_name   Bucket to which the object is being copied.
    dst_key_name      The name of the new object.
    metadata          A dict containing new metadata that you want
                      to associate with this object.  If this is None
                      the metadata of the original object will be
                      copied to the new object.
    preserve_acl      If True, the ACL from the original object
                      will be copied to the new object.  If False
                      the new object will have the default ACL.
    """
    s3 = boto.connect_s3()
    bucket = s3.lookup(src_bucket_name)

    # Lookup the existing object in S3
    key = bucket.lookup(src_key_name)

    # Copy the key back on to itself, with new metadata
    return key.copy(dst_bucket_name, dst_key_name,
                    metadata=metadata, preserve_acl=preserve_acl)

0

在s3中没有直接重命名文件的方法。你需要做的是用新名称复制现有文件(只需设置目标键)并删除旧文件。谢谢


-6
//Copy the object
AmazonS3Client s3 = new AmazonS3Client("AWSAccesKey", "AWSSecretKey");

CopyObjectRequest copyRequest = new CopyObjectRequest()
      .WithSourceBucket("SourceBucket")
      .WithSourceKey("SourceKey")
      .WithDestinationBucket("DestinationBucket")
      .WithDestinationKey("DestinationKey")
      .WithCannedACL(S3CannedACL.PublicRead);
s3.CopyObject(copyRequest);

//Delete the original
DeleteObjectRequest deleteRequest = new DeleteObjectRequest()
       .WithBucketName("SourceBucket")
       .WithKey("SourceKey");
s3.DeleteObject(deleteRequest);

21
这是使用AWS SDK for .NET提供的解决方案,而不是使用boto所请求的解决方案。boto是一个Python软件包,提供了与亚马逊网络服务的接口。 - Steffen Opel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接