我在S3中有大约1000个以
命名的对象abcyearmonthday1
abcyearmonthday2
abcyearmonthday3
...
想要将它们重命名为
abc/year/month/day/1
abc/year/month/day/2
abc/year/month/day/3
我怎么能通过boto3来做到这一点。有更简单的方法吗?
答案 0 :(得分:4)
如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()
答案 1 :(得分:1)
没有直接重命名S3对象的方法。 以下两个步骤需要执行:
答案 2 :(得分:0)
我遇到了同样的问题(就我而言,我想使用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()