Download file from AWS S3 using Python

Taukheer picture Taukheer · Apr 30, 2018 · Viewed 52.5k times · Source

I am trying to download a file from Amazon S3 bucket to my local using the below code but I get an error saying "Unable to locate credentials"

Given below is the code I have written:

from boto3.session import Session
import boto3

ACCESS_KEY = 'ABC'
SECRET_KEY = 'XYZ'

session = Session(aws_access_key_id=ACCESS_KEY,
              aws_secret_access_key=SECRET_KEY)
s3 = session.resource('s3')
your_bucket = s3.Bucket('bucket_name')

for s3_file in your_bucket.objects.all():
    print(s3_file.key) # prints the contents of bucket

s3 = boto3.client ('s3')

s3.download_file('your_bucket','k.png','/Users/username/Desktop/k.png')

Could anyone help me on this. Thanks.

Answer

Joaquín Bucca picture Joaquín Bucca · Apr 30, 2018

You are not using the session you created to download the file, you're using s3 client you created. If you want to use the client you need to specify credentials.

your_bucket.download_file('k.png', '/Users/username/Desktop/k.png')

or

s3 = boto3.client('s3', aws_access_key_id=... , aws_secret_access_key=...)
s3.download_file('your_bucket','k.png','/Users/username/Desktop/k.png')