Listing contents of a bucket with boto3 Listing contents of a bucket with boto3 python python

Listing contents of a bucket with boto3


One way to see the contents would be:

for my_bucket_object in my_bucket.objects.all():    print(my_bucket_object)


This is similar to an 'ls' but it does not take into account the prefix folder convention and will list the objects in the bucket. It's left up to the reader to filter out prefixes which are part of the Key name.

In Python 2:

from boto.s3.connection import S3Connectionconn = S3Connection() # assumes boto.cfg setupbucket = conn.get_bucket('bucket_name')for obj in bucket.get_all_keys():    print(obj.key)

In Python 3:

from boto3 import clientconn = client('s3')  # again assumes boto.cfg setup, assume AWS S3for key in conn.list_objects(Bucket='bucket_name')['Contents']:    print(key['Key'])


I'm assuming you have configured authentication separately.

import boto3s3 = boto3.resource('s3')my_bucket = s3.Bucket('bucket_name')for file in my_bucket.objects.all():    print(file.key)