1

I am trying to zip a file on s3 using the code below,, the issue is, file seems to be created but when i try to open the zip file it shows error that archive is not valid. any idea what I am doing wrong here...

code i am using is as below...

def upload_zip_file(event,context):    
    try:
        bucket_name ="s3_bucket"
        bucket_path ="files"
        s3 = boto3.client('s3')
        data_io = BytesIO()
        filename = "FILE.zip"
        funct_name ="FILE.json"
        zip_buffer = io.BytesIO()
        with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zipper:
            infile_object = s3.get_object(Bucket=bucket_name, Key=bucket_path +"/"+ funct_name) 
            infile_content = infile_object['Body'].read()
            zipper.writestr(filename, infile_content)
            s3.put_object(Bucket=bucket_name, Key=bucket_path +"/"+filename, Body=zip_buffer.getvalue())            
            
    except Exception:
        print(traceback.format_exc())
Faisal Niazi
  • 85
  • 1
  • 8

1 Answers1

0

You need to move the put_object, outside of the with, so that the file handle is properly closed.

zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zipper:
    infile_object = s3.get_object(Bucket=bucket_name, Key=filename) 
    infile_content = infile_object['Body'].read()
    zipper.writestr(filename, infile_content)
    
s3.put_object(Bucket=bucket_name, Key='test.zip', Body=zip_buffer.getvalue()) 
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194