I want to unzip file from one folder to another folder in s3 using lambda function python I have one code for this but in this code file are automatically repeated when we upload file

0 votes
import json
import boto3
from io import BytesIO
import zipfile

def lambda_handler(event, context):
    # TODO implement
    
    s3_resource = boto3.resource('s3')
    source_bucket = 'source-b12'
    target_bucket = 'destination-b12'

    my_bucket = s3_resource.Bucket(source_bucket)

    for file in my_bucket.objects.all():
        if(str(file.key).endswith('.zip')):
            zip_obj = s3_resource.Object(bucket_name=source_bucket, key=file.key)
            buffer = BytesIO(zip_obj.get()["Body"].read())
            
            z = zipfile.ZipFile(buffer)
            for filename in z.namelist():
                file_info = z.getinfo(filename)
                try:
                    response = s3_resource.meta.client.upload_fileobj(
                        z.open(filename),
                        Bucket=target_bucket,
                        Key=f'{filename}'
                    )
                except Exception as e:
                    print(e)
        else:
            print(file.key+ ' is not a zip file.')
Apr 15, 2022 in Python by anonymous

edited Mar 4, 2025 292 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP