[Python] Move files from one S3 to another using Boto3 in Python from multiple sub bucket...

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have below code to move the file from one S3 bucket to another which works perfectly. The catch here is while copying the files it copies the S3 bucket as well, instead I wanted to copy only the file from the bucket.

    Source bucket - bucket-source/Source-First/ --> This file has multiple .xlsx files
    Target bucket - bucket-target

    I want only the files from bucket-source/Source-First/ copied to bucket-target. Currently it copies along with the bucket name Source-First/

    bucket-target/Source-First/File1.xlsx
    bucket-target/Source-First/File2.xlsx

    But I wanted only the files to be copied

    bucket-target/File1.xlsx<br>
    bucket-target/File2.xlsx


    import boto3

    bucket_from = "bucket-source"
    bucket_to = "bucket-target"

    s3 = boto3.resource('s3')

    src = s3.Bucket(bucket_from)
    tgt = s3.Bucket(bucket_to)

    for archive in src.objects.filter(Prefix='Source-First/'):

    if archive.key.endswith('.xlsx'):

    CopySource = {'Bucket': archive.bucket_name, 'Key': archive.key}
    tgt.copy(CopySource, archive.key)
    archive.delete()

    Continue reading...

Compartilhe esta Página