Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i get the list of objects in S3 having Key Error and exceptions

I am new to this AWS boto3 concepts .The below code is giving a Key error  and some exception  that i am trying to execute can someone look to it and try to solve if any errors?

import boto3

def list_s3_objects(bucket_name):
    s3 = boto3.client('s3')
    objects = []
    try:
        response = s3.list_objects_v2(Bucket=bucket_name)
        for obj in response['Contents']:
            objects.append(obj['Key'])
    except Exception as e:
        print(f"An error occurred in the following ie,: {e}")
    return objects

def main():
    bucket_name = 'name of my bucket'
    objects = list_s3_objects(bucket_name)
    print("S3 Objects to be created are:")
    for obj in objects:
        print(obj)

if __name__ == "__main__":
    main()

I tried different excepts to handle and even my login details were correct . But it also showed as key error . I just wanted to print my s3 bucket objects .

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The below code lists the s3 objects as you have specified. Here I have added the paginator and botocore.exceptions for checking exception.  Thank you

import boto3
from botocore.exceptions import ClientError

def list_s3_objects(bucket_name):
    s3 = boto3.client('s3')
    objects = []
    try:
        paginator = s3.get_paginator('list_objects_v2')
        for page in paginator.paginate(Bucket=bucket_name):
            if 'Contents' in page:
                for obj in page['Contents']:
                    objects.append(obj['Key'])
    except ClientError as e:
        print(f"Error occurred is: {e}")
    return objects

def main():
    bucket_name = 'my-bucket'
    objects = list_s3_objects(bucket_name)
    print("S3 Objects are :")
    for obj in objects:
        print(obj)

if __name__ == "__main__":
    main()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading