[python] Open S3 object as a string with Boto3

I'm aware that with Boto 2 it's possible to open an S3 object as a string with: get_contents_as_string()

Is there an equivalent function in boto3 ?

This question is related to python amazon-s3 boto boto3

The answer is


read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))


This isn't in the boto3 documentation. This worked for me:

object.get()["Body"].read()

object being an s3 object: http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object


Python3 + Using boto3 API approach.

By using S3.Client.download_fileobj API and Python file-like object, S3 Object content can be retrieved to memory.

Since the retrieved content is bytes, in order to convert to str, it need to be decoded.

import io
import boto3

client = boto3.client('s3')
bytes_buffer = io.BytesIO()
client.download_fileobj(Bucket=bucket_name, Key=object_key, Fileobj=bytes_buffer)
byte_value = bytes_buffer.getvalue()
str_value = byte_value.decode() #python3, default decoding is utf-8

If body contains a io.StringIO, you have to do like below:

object.get()['Body'].getvalue()

Questions with python tag:

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Upgrade to python 3.8 using conda Unable to allocate array with shape and data type How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip How to prevent Google Colab from disconnecting? "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? "E: Unable to locate package python-pip" on Ubuntu 18.04 Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' Jupyter Notebook not saving: '_xsrf' argument missing from post How to Install pip for python 3.7 on Ubuntu 18? Python: 'ModuleNotFoundError' when trying to import module from imported package OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website How to setup virtual environment for Python in VS Code? Pylint "unresolved import" error in Visual Studio Code Pandas Merging 101 Numpy, multiply array with scalar What is the meaning of "Failed building wheel for X" in pip install? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed Could not install packages due to an EnvironmentError: [Errno 13] OpenCV !_src.empty() in function 'cvtColor' error ConvergenceWarning: Liblinear failed to converge, increase the number of iterations How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How do I install opencv using pip? How do I install Python packages in Google's Colab? How do I use TensorFlow GPU? How to upgrade Python version to 3.7? How to resolve TypeError: can only concatenate str (not "int") to str How can I install a previous version of Python 3 in macOS using homebrew? Flask at first run: Do not use the development server in a production environment TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array What is the difference between Jupyter Notebook and JupyterLab? Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" How do I resolve a TesseractNotFoundError? Trying to merge 2 dataframes but get ValueError Authentication plugin 'caching_sha2_password' is not supported Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

Questions with amazon-s3 tag:

How to specify credentials when connecting to boto3 S3? AWS S3 CLI - Could not connect to the endpoint URL How to write a file or data to an S3 object using boto3 The AWS Access Key Id does not exist in our records AccessDenied for ListObjects for S3 bucket when permissions are s3:* Save Dataframe to csv directly to s3 Python Listing files in a specific "folder" of a AWS S3 bucket How to get response from S3 getObject in Node.js? Getting Access Denied when calling the PutObject operation with bucket-level permission Read file content from S3 bucket with boto3 AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden Retrieving subfolders names in S3 bucket from boto3 check if a key exists in a bucket in s3 using boto3 Open S3 object as a string with Boto3 Boto3 to download all files from a S3 Bucket AWS S3 - How to fix 'The request signature we calculated does not match the signature' error? Listing contents of a bucket with boto3 AWS EFS vs EBS vs S3 (differences & when to use?) Amazon S3 exception: "The specified key does not exist" Upload a file to Amazon S3 with NodeJS Downloading folders from aws s3, cp or sync? Read file from aws s3 bucket using node fs URL for public Amazon S3 bucket The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256 Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint FTP/SFTP access to an Amazon S3 Bucket Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache How to rename files and folder in Amazon S3? Amazon AWS Filezilla transfer permission denied Amazon S3 direct file upload from client browser - private key disclosure S3 - Access-Control-Allow-Origin Header Access files stored on Amazon S3 through web browser S3 Static Website Hosting Route All Paths to Index.html How to upload a file to directory in S3 bucket using boto How to Configure SSL for Amazon S3 bucket Amazon S3 upload file and get URL How to delete files recursively from an S3 bucket Best way to move files between S3 buckets? AWS S3 copy files and folders between two buckets AWS S3: how do I see how much disk space is using Downloading an entire S3 bucket? AmazonS3 putObject with InputStream length example How to check if a specified key exists in a given S3 bucket using Java How to list all AWS S3 objects in a bucket using Java How to format a URL to get a file from Amazon S3? Setting up FTP on Amazon Cloud Server Upload folder with subfolders using S3 and the AWS console How do you search an amazon s3 bucket? S3 limit to objects in a bucket

Questions with boto tag:

How to write a file or data to an S3 object using boto3 Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials How to handle errors with boto3? Open S3 object as a string with Boto3 Listing contents of a bucket with boto3 How to save S3 object to a file using boto3 How to upload a file to directory in S3 bucket using boto How do I install boto? Amazon S3 boto - how to create a folder?

Questions with boto3 tag:

How to specify credentials when connecting to boto3 S3? Difference in boto3 between resource, client, and session? boto3 client NoRegionError: You must specify a region error only sometimes How to write a file or data to an S3 object using boto3 Save Dataframe to csv directly to s3 Python Read file content from S3 bucket with boto3 Retrieving subfolders names in S3 bucket from boto3 check if a key exists in a bucket in s3 using boto3 Unable to install boto3 How to choose an AWS profile when using boto3 to connect to CloudFront Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials How to handle errors with boto3? Open S3 object as a string with Boto3 Boto3 to download all files from a S3 Bucket Listing contents of a bucket with boto3 How to save S3 object to a file using boto3