This post explains how to read a file from S3 bucket using Python AWS Lambda
function. We will use boto3
apis to
read files from S3 bucket.
import boto3
s3_client = boto3.client("s3")
S3_BUCKET_NAME = 'BUCKET_NAME'
Write below code in Lambda function and replace the OBJECT_KEY
.
def lambda_handler(event, context):
object_key = "OBJECT_KEY" # replace object key
file_content = s3_client.get_object(
Bucket=S3_BUCKET, Key=object_key)["Body"].read()
print(file_content)
import boto3
s3_client = boto3.client("s3")
S3_BUCKET = 'BUCKET_NAME'
def lambda_handler(event, context):
object_key = "OBJECT_KEY" # replace object key
file_content = s3_client.get_object(
Bucket=S3_BUCKET, Key=object_key)["Body"].read()
print(file_content)
import json
import boto3
s3_client = boto3.client("s3")
S3_BUCKET = 'BUCKET_NAME'
S3_PREFIX = 'BUCKET_PREFIX'
Write below code in Lambda handler to list and read all the files from a S3 prefix. Replace BUCKET_NAME
and BUCKET_PREFIX
.
def lambda_handler(event, context):
response = s3_client.list_objects_v2(
Bucket=S3_BUCKET, Prefix=S3_PREFIX, StartAfter=S3_PREFIX,)
s3_files = response["Contents"]
for s3_file in s3_files:
file_content = json.loads(s3_client.get_object(
Bucket=S3_BUCKET, Key=s3_file["Key"])["Body"].read())
print(file_content)
import json
import boto3
s3_client = boto3.client("s3")
S3_BUCKET = 'BUCKET_NAME'
S3_PREFIX = 'BUCKET_PREFIX'
def lambda_handler(event, context):
response = s3_client.list_objects_v2(
Bucket=S3_BUCKET, Prefix=S3_PREFIX, StartAfter=S3_PREFIX,)
s3_files = response["Contents"]
for s3_file in s3_files:
file_content = json.loads(s3_client.get_object(
Bucket=S3_BUCKET, Key=s3_file["Key"])["Body"].read())
print(file_content)
Category: AWS