使用 boto3 从 S3 存储桶下载多个文件

Download multiple files from S3 bucket using boto3

我有一个包含大量 uuids

的 csv 文件

我想使用 boto3 编写 python 脚本,其中:

  1. 连接到 AWS S3 存储桶
  2. 使用 CSV 中包含的每个 uuid 来复制包含的文件

文件都包含在这样的文件路径中: BUCKET/ORG/FOLDER1/UUID/DATA/FILE.PNG 但是,DATA/中包含的文件可以是不同的文件类型。

  1. 将复制的文件放入新的 S3 存储桶

到目前为止,我已经成功连接到 s3 存储桶并使用 boto3 在 python 中检查了它的内容,但需要帮助实现其余部分

import boto3

#Create Session
session = boto3.Session(
    aws_access_key_id='ACCESS_KEY_ID',
    aws_secret_access_key='SECRET_ACCESS_KEY',
)

#Initiate S3 Resource
s3 = session.resource('s3')

                  
your_bucket = s3.Bucket('BUCKET-NAME')


for s3_file in your_bucket.objects.all():
    print(s3_file.key) # prints the contents of bucket

要读取 CSV 文件,您可以使用 csv 库(参见:https://docs.python.org/fr/3.6/library/csv.html示例

import csv
with open('file.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

要将文件推送到新存储桶,可以使用copy方法(参见:https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.copy

示例

import boto3
s3 = boto3.resource('s3')
source = {
      'Bucket': 'BUCKET-NAME',
      'Key': 'mykey'
}
bucket = s3.Bucket('SECOND_BUCKET-NAME')
bucket.copy(source, 'SECOND_BUCKET-NAME')