在跨帐户 s3 存储桶之间复制文件时重命名文件

Rename files while copying files between cross account s3 buckets

我正在跨账户 s3 存储桶之间复制多个镶木地板文件。当我将它们复制到目标存储桶时,我想重命名这些文件。

import boto3
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3')

bucket = 'sourcebucket'
folder_path = 'source_folder/'

resp = s3_client.list_objects(Bucket=bucket, Prefix=folder_path)
keys = []
for obj in resp['Contents']:
    keys.append(obj['Key'])


for key in keys:
    copy_source ={
        'Bucket': 'sourcebucket',
        'Key': key
    }
    file_name = key.split('/')[-1]
     s3_file = 'dest_folder/'+'xyz'+file_name
    bucketdest = s3_resource.Bucket('destinationbucket')
    bucketdest.copy(copy_source,s3_file,ExtraArgs={'GrantFullControl':'id = " "'})

这是我试过的。我可以在我的目标存储桶中看到具有新名称的文件,但它们没有实际数据。

谢谢!

你的代码对我来说工作得很好! (但是,我 运行 它没有 ExtraArgs 因为我没有 ID。)

当我在存储桶之间复制对象时,我使用的规则是:

  • 如果可能,'pull' 文件来自 不同的帐户
  • 如果'pushing'文件另一个账户,我设置ExtraArgs={'ACL':'bucket-owner-full-control'}

我怀疑这个小改动会影响对象的内容。

顺便说一下,使用 客户端方法 资源方法可能是个好主意。混合使用它们会导致代码混乱和潜在问题。

所以,您可以使用类似的东西:

客户端方法:

response = s3_client.list_objects(Bucket=bucket, Prefix=source_prefix)

for object in response['Contents']:
    copy_source ={
        'Bucket': source_bucket,
        'Key': object['Key']
    }
    s3_client.copy_object(
        Bucket = target_bucket,
        Key = 'dest_folder/' + 'xyz' + key.split('/')[-1],
        CopySource = copy_source,
        ACL = 'bucket-owner-full-control'
    )

或者您可以使用:

资源方法:

for object in s3_resource.Bucket(source_bucket).objects.Filter(Prefix=source_prefix):
    copy_source ={
        'Bucket': source_bucket,
        'Key': object.key
    }
    s3_resource.Bucket(target_bucket).copy(
        CopySource = copy_source,
        Key = 'dest_folder/' + 'xyz' + key.split('/')[-1],
        ExtraArgs={'ACL':'bucket-owner-full-control'}
    )

(警告:我没有测试这些片段。)