Write a Python script to list all objects in a given S3 bucket and log their names. Include basic error handling for cases such as missing buckets or incorrect permissions.
1Times asked
Aug 2026Last seen
Aug 2026First seen
💡 Model Answer
Here is a concise script that uses boto3 to list objects in an S3 bucket with error handling:
python
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client('s3')
bucket_name = 'my-bucket'
try:
paginator = s3.get_paginator('list_objects_v2')
for page in paginator.paginate(Bucket=bucket_name):
for obj in page.get('Contents', []):
print(obj['Key'])
except ClientError as e:
error_code = e.response['Error']['Code']
if error_code == 'NoSuchBucket':
print(f"Bucket {bucket_name} does not exist.")
elif error_code == 'AccessDenied':
print(f"Access denied to bucket {bucket_name}. Check IAM permissions.")
else:
print(f"Unexpected error: {e}")The script uses a paginator to handle buckets with many objects, prints each key, and catches common errors such as missing buckets or insufficient permissions. The ClientError exception provides an error code that we can use to give clear feedback to the user.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500