欢迎访问宙启技术站
智能推送

使用Boto3将数据从AWSS3复制到另一个S3存储桶

发布时间:2023-12-25 22:19:28

使用Boto3将数据从一个AWSS3存储桶复制到另一个S3存储桶是一个简单而常见的任务。以下是一个使用Python和Boto3的例子,演示了如何完成这个任务。

首先,确保已经安装了Boto3库。可以使用以下命令通过pip进行安装:

pip install boto3

接下来,添加必要的库引用:

import boto3

然后,创建一个S3客户端:

s3_client = boto3.client('s3')

接下来,指定源存储桶和目标存储桶的名称:

source_bucket_name = 'source-bucket'
destination_bucket_name = 'destination-bucket'

然后,获取源存储桶中的所有对象列表:

response = s3_client.list_objects(Bucket=source_bucket_name)

遍历响应中的所有对象,针对每个对象进行复制操作:

for obj in response['Contents']:
    # 获取对象的键(key),即对象的路径和名称
    obj_key = obj['Key']
  
    # 复制对象到目标存储桶中
    s3_client.copy_object(
        Bucket=destination_bucket_name,
        CopySource={'Bucket': source_bucket_name, 'Key': obj_key},
        Key=obj_key
    )
    print(f"{obj_key} 已复制到 {destination_bucket_name}")

最后,添加错误处理和完整的脚本结束:

import boto3

s3_client = boto3.client('s3')

source_bucket_name = 'source-bucket'
destination_bucket_name = 'destination-bucket'

try:
    response = s3_client.list_objects(Bucket=source_bucket_name)

    for obj in response['Contents']:
        obj_key = obj['Key']
  
        s3_client.copy_object(
            Bucket=destination_bucket_name,
            CopySource={'Bucket': source_bucket_name, 'Key': obj_key},
            Key=obj_key
        )
        print(f"{obj_key} 已复制到 {destination_bucket_name}")

except Exception as e:
    print(e)

这个例子将源存储桶中的每个对象复制到目标存储桶中,并在每个对象成功复制后打印出一条消息。

请确保在代码中替换源存储桶和目标存储桶的名称,并根据需要添加适当的错误处理和日志记录。