How to read a text file (line by line) from AWS S3?

Let’s talk about how we can read a raw text file (line by line) from Amazon S3 buckets using high-level AWS s3 commands and Python. Check the more detail on AWS S3 doc. First, you need to create a new python file called readtext.py and implement the following codes.

1. Download and install boto3 library

$ pip install boto3

2. Read a text file (line by line) from AWS S3

# importing the boto3 library 
import boto3
# connect to S3 using boto3 client
s3_client = boto3.client(service_name='s3')
# get S3 object
result = s3_client.get_object(Bucket='<bucket-name>', Key='<file-name-to-read') 
#Read a text file line by line using splitlines object
for line in result["Body"].read().splitlines():
  each_line = line.decode('utf-8')
  print(each_line)

That’s it. I hope this will help. ?
Photo: https://www.brandeps.com

Leave a Reply

Your email address will not be published. Required fields are marked *