【问题标题】:Transfer files from one S3 bucket to another S3 bucket using python boto3使用 python boto3 将文件从一个 S3 存储桶传输到另一个 S3 存储桶
【发布时间】:2018-06-02 06:37:52
【问题描述】:

我想将文件从一个 s3 存储桶路径(例如 B1/x/*)传输到另一个 S3 存储桶(例如 B2/y/*),其中 B1 和 B2 是两个 s3 存储桶,x 和 y 是其中包含 csv 文件的文件夹分别。

我写了下面的脚本来做到这一点。但我收到错误“object_list”未定义。此外,我不确定它是否会执行传输文件的工作。

参考下面的脚本:

import boto3
s3 = boto3.client("s3")
# list_objects_v2() give more info

more_objects=True
found_token = True
while more_objects :
  if found_token :
    response= s3.list_objects_v2(
      Bucket="B1", 
      Prefix="x/",
      Delimiter="/")
  else:   
    response= s3.list_objects_v2(
      Bucket="B1",
      ContinuationToken=found_token,
      Prefix="x/",
      Delimiter="/")
  # use copy_object or copy_from
  for source in object_list["Contents"]:
    raw_name = source["Key"].split("/")[-1] 
    new_name = "new_structure/{}".format(raw_name)
    s3.copy_from(CopySource='B1/x')      
    # Now check there is more objects to list
    if "NextContinuationToken" in response:
      found_token = response["NextContinuationToken"]
      more_objects = True
    else:
      more_objects = False

如果有人可以帮助我对上述脚本进行更改,那将非常有帮助。

谢谢

【问题讨论】:

    标签: python-3.x amazon-s3 amazon boto3


    【解决方案1】:

    您可以使用下面的代码将文件从一个存储桶传输到另一个存储桶,就像您的分层文件夹结构一样。在这里您不必定义任何特定的键或文件夹结构,代码会处理这些:

    import boto3
    s3 = boto3.resource('s3')
    src_bucket = s3.Bucket('bucket_name')
    dest_bucket = s3.Bucket('bucket_name')
    dest_bucket.objects.all().delete()  #this is optional clean bucket
    for obj in src_bucket.objects.all():
        s3.Object('dest_bucket', obj.key).put(Body=obj.get()["Body"].read())
    

    如果您想在文件移动后清除源存储桶,您可以 在代码末尾使用src_bucket.objects.all().delete() 来清理 源桶。

    【讨论】:

      【解决方案2】:

      如果您的脚本在本地服务器上运行并且想要访问两个存储桶以将文件从一个 s3 存储桶传输到另一个存储桶,您可以按照以下代码。这会在“bucket1”中创建文件副本到“bucket2”中的“sample”文件夹”。

      import boto3
      s3 = boto3.resource('s3')
      src_bucket = s3.Bucket('bucket1')
      dest_bucket = s3.Bucket('bucket2')
      for obj in src_bucket.objects.all():
          filename= obj.key.split('/')[-1]
          dest_bucket.put_object(Key='sample/' + filename, Body=obj.get()["Body"].read())
      

      我想在从源存储桶复制后删除文件,下面的代码可以在复制后在循环中使用。

      s3.Object(src_bucket, obj.key).delete()
      

      【讨论】:

        猜你喜欢
        • 2023-02-01
        • 2020-05-29
        • 1970-01-01
        • 1970-01-01
        • 2022-06-12
        • 2018-05-08
        • 1970-01-01
        • 2018-11-22
        • 1970-01-01
        相关资源
        最近更新 更多