Acessing directory in bucket S3 and getting the itens

I am having some issues understanding the documentation, I have something like this in my bucket:

—- videos
      —-carvideos
         Tesla.video
         Chevrolet.video
      Car.png
      Bike.png

—-Files

And I want to access the video directory and get the car.png file, And to enter the carvideos directory and get all the videos in it.How do I do that?

My code:

import boto3
s3 =boto3.resource(‘s3’, access_key, secret_acess_key)


bucket = s3.Bucket(‘name of my bucket’)

Upvotes: 0

Views: 38

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269320

You can access the car.png file like this:

import boto3

s3_resource = boto3.resource('s3')

s3.Object('mybucket', 'videos/Car.png').download_file('/tmp/Car.png')

Note that the filename (Key) of the object includes the full path to the object.

To obtain a listing of all objects in the carvideos directory, you can use:

bucket = s3_resource.Bucket('mybucket')

objects = bucket.objects.filter(Prefix='videos/carvideos/')

for object in objects:
  print(object.Key)

Upvotes: 1

Related Questions