Downloading File Content as String From S3 in Python

  • Last updated Apr 25, 2024

Follow these steps to download the content of a file as a string from Amazon S3 using the AWS Boto3 library in Python:

  1. Install Boto3 Python library:
  2. pip install boto3
    
  3. Here's a sample code to download the content of a file as a string from Amazon S3 in Python:
  4. import boto3
    from botocore.exceptions import ClientError
    import io
    
    ACCESS_SECRET = "your aws access secret"
    ACCESS_KEY = "your aws access key"
    
    s3_client = boto3.client('s3', region_name='us-east-1', aws_access_key_id=ACCESS_KEY,
                             aws_secret_access_key=ACCESS_SECRET)
    
    bucket_name = "bucket-one"
    
    file_name = "example.txt"
    
    # file path in s3
    key = "folder/"+file_name
    
    # download file
    try:
        str_content = ""
        bytes_buffer = io.BytesIO()
    
        s3_client.download_fileobj(
            Bucket=bucket_name, Key=key, Fileobj=bytes_buffer)
    
        byte_value = bytes_buffer.getvalue()
        str_content = byte_value.decode('utf-8')
        print("File content = ", str_content)
    except ClientError as ex:
        print("Error: ", ex)