【问题标题】:How to rename objects boto3 S3?如何重命名对象 boto3 S3?
【发布时间】:2020-06-19 03:21:37
【问题描述】:

我在 S3 中有大约 1000 个以命名的对象

abcyearmonthday1
abcyearmonthday2
abcyearmonthday3
...

想将它们重命名为

abc/year/month/day/1
abc/year/month/day/2
abc/year/month/day/3

我怎么能通过 boto3.有没有更简单的方法?

【问题讨论】:

标签: amazon-s3 boto3


【解决方案1】:

Boto3/S3: Renaming an object using copy_object中所述

您不能在 S3 中重命名对象,您必须使用新名称复制对象,然后删除旧对象

s3 = boto3.resource('s3')
s3.Object('my_bucket','my_file_new').copy_from(CopySource='my_bucket/my_file_old')
s3.Object('my_bucket','my_file_old').delete()

【讨论】:

    【解决方案2】:

    没有直接重命名 S3 对象的方法。 需要执行以下两个步骤:

    1. 使用新名称将 S3 对象复制到相同位置。
    2. 然后删除旧对象。

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题(在我的情况下,我想使用 Redshift UNLOAD 命令重命名在 S3 中生成的文件)。我解决了创建一个 boto3 会话,然后逐个文件复制删除文件。

      喜欢

      import boto3
      
      session = boto3.session.Session(aws_access_key_id=my_access_key_id,aws_secret_access_key=my_secret_access_key).resource('s3')
      
      # Save in a list the tuples of filenames (with prefix): [(old_s3_file_path, new_s3_file_path), ..., ()] e.g. of tuple ('prefix/old_filename.csv000', 'prefix/new_filename.csv')
      s3_files_to_rename = []
      s3_files_to_rename.append((old_file, new_file))
      
      for pair in s3_files_to_rename:
          old_file = pair[0]
          new_file = pair[1]
      
          s3_session.Object(s3_bucket_name, new_file).copy_from(CopySource=s3_bucket_name+'/'+old_file)
          s3_session.Object(s3_bucket_name, old_file).delete()
      

      【讨论】:

        猜你喜欢
        • 2015-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-27
        • 1970-01-01
        • 2011-02-12
        • 2020-07-07
        • 2015-06-05
        相关资源
        最近更新 更多