I have this code to download all the files from a buckets AWS S3
JavaScript
x
23
23
1
import os
2
import boto3
3
4
#initiate s3 resource
5
s3 = boto3.resource('s3')
6
7
s3 = boto3.resource(
8
's3',
9
aws_access_key_id = '__________',
10
aws_secret_access_key = '________',
11
region_name = '______'
12
)
13
14
15
# select bucket
16
my_bucket = s3.Bucket('MainBucket')
17
18
# download file into current directory
19
for s3_object in my_bucket.objects.all():
20
# Need to split s3_object.key into path and file name, else it will give error file not found.
21
path, filename = os.path.split(s3_object.key)
22
my_bucket.download_file(s3_object.key, filename)
23
Inside that bucket, I have a folder called “pictures”
How can I get the files only in my folder?
My try:
JavaScript
1
2
1
s3.Bucket('MainBucket/pictures')
2
Advertisement
Answer
Inside that bucket, I have a folder called “pictures”
How can I get the files only in my folder?
You can get the files only in the “pictures” folder by providing a prefix:
JavaScript
1
9
1
# select bucket
2
my_bucket = s3.Bucket('MainBucket')
3
4
# download file into current directory
5
for s3_object in my_bucket.objects.filter(Prefix='pictures/'): <-- FILTER 'PICTURES'
6
# Need to split s3_object.key into path and file name, else it will give error file not found.
7
path, filename = os.path.split(s3_object.key)
8
my_bucket.download_file(s3_object.key, filename)
9