Python example for downloading s3 file in Python with boto3 library
In this tutorial we are going to develop example program to download file from AWS s3 bucket using the highly popular Python boto3 library. You can use Amazon s3 bucket to store the objects such as files, images, videos and files of all the types. Python boto3 is very popular library to work with the s3 objects in Python code. As a python developer you should learn the boto3 library if you are working on the AWS projects.
What is Boto3?
Boto3 is AWS SDK for Python developers that allow the developers to integrate Python application with AWs services such as Amazon S3, Amazon EC2, Amazon DynamoDB and many other AWS services. The Boto3 library provides the functions to connect to supported AWS services and interact with them. You have to provide valid credentials to connect to your AWS service from your Python program. In this example we are going to download file from the S3 bucket.
I am assuming that you have valid Amazon AWS account and you generated keys for using in your Python program.
How to install Boto3 Library on Python 3?
I am using Python 3.8 which is the latest version of Python. To install Boto3 on Python 3 you can use following command:
apt install python3-boto3
Above command will install Boto3 on your Python 3 installation.
Downloading file from AWS s3 using boto3
First all we have to import all the necessary boto3 library. You have to import following in your program:
import boto3
from boto3.session import Session
from boto3.s3.transfer import S3Transfer
After this we can define the necessary AWS credentials as shown below:
BUCKET =""
BUCKET_FILE=""
SAVE_TO=""
AWS_ACCESS_KEY_ID = ""
AWS_SECRET_ACCESS_KEY = ""
AWS_REGION = "eu-north-1"
Now we can write the program for downloading the file from s3. Following code actually downloads the file from s3:
client_s3 = boto3.client("s3",AWS_REGION,aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
transfer = S3Transfer(client_s3)
transfer.download_file(BUCKET,BUCKET_FILE,SAVE_TO)
Here is the complete program that downloads a file from s3 location:
import boto3
from boto3.session import Session
from boto3.s3.transfer import S3Transfer
BUCKET =""
BUCKET_FILE=""
SAVE_TO=""
AWS_ACCESS_KEY_ID = ""
AWS_SECRET_ACCESS_KEY = ""
AWS_REGION = "eu-north-1"
client_s3 = boto3.client("s3",AWS_REGION,aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
transfer = S3Transfer(client_s3)
transfer.download_file(BUCKET,BUCKET_FILE,SAVE_TO)
Here is the screen shot of the program.
In this tutorial we have learned how to use the Boto3 library to download file from Amazon s3 object storage server.
Check more tutorials: