Python: Download File from AWS S3 Using boto3

6/15/2021 5:31:37 PM
The following python code uses boto3 library to download a file from S3, convert it to a string, and return it to the calling function. This example uses UTF-8 decoding.
import boto3


def download_file(bucket, key):
    print("aws.s3.download_file: " + bucket + " | " + key)

    
    #use default credentials
    s3_client = boto3.client('s3')

    #use aws credentials
    # session = boto3.Session(
    #     aws_access_key_id="MY_ACCESS_KEY",
    #     aws_secret_access_key="MY_SECRET_KEY")
    # s3_client = session.client('s3')

    #use aws profile    
    # session = boto3.Session(profile_name='my_profile_name')
    # s3_client = session.client('s3')


    s3_response = s3_client.get_object(Bucket=bucket, Key=key)
    # print(s3_response)

    raw_string = s3_response['Body'].read()
    # print(raw_string)

    utf_8_string = raw_string.decode("utf-8")
    #alt decoding
    #utf_8_string = raw_string.decode("ISO-8859-1")    
    #print(utf_8_string)

    # strip whitespace
    utf_8_string = utf_8_string.strip()
    #print(utf_8_string)


    return(utf_8_string)