Downloading File Content as String From S3 in Python
Follow these steps to download the content of a file as a string from Amazon S3 using the AWS Boto3 library in Python:
- Install Boto3 Python library:
- Here's a sample code to download the content of a file as a string from Amazon S3 in Python:
pip install boto3
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)