【发布时间】: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.有没有更简单的方法?
【问题讨论】:
我在 S3 中有大约 1000 个以命名的对象
abcyearmonthday1
abcyearmonthday2
abcyearmonthday3
...
想将它们重命名为
abc/year/month/day/1
abc/year/month/day/2
abc/year/month/day/3
我怎么能通过 boto3.有没有更简单的方法?
【问题讨论】:
如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()
【讨论】:
没有直接重命名 S3 对象的方法。 需要执行以下两个步骤:
【讨论】:
我遇到了同样的问题(在我的情况下,我想使用 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()
【讨论】: