0

I am new to the AWS services.I am trying to read a csv file from AWS S3 bucket but I cannot read or get any output from AWS lambda.

import json
import boto3
import csv
s3_client = boto3.client('s3')
def lambda_handler(event, context):
    # TODO implement
    try:
        bucket_name = event["Records"][0]["s3"]["bucket"]["name"]
        s3_file_name = event["Records"][0]["s3"]["object"]["key"]
    
        csv_file = s3_client.get_object(Bucket=bucket_name, Key=s3_file_name)
        data = csv_file['Body'].read().splitlines(True)
        reader = csv.reader(data)
        print(reader)
    except Exception as err:
        print(err)
    

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
}

I am getting this output but I don't get data from my print line why is that?
please help me!

aws issue

here is s3req test event enter image description here

3
  • What is s3req test event? Commented Sep 30, 2021 at 5:03
  • 1
    Please don't post event as screenshot, but properly formatted json code block. Commented Sep 30, 2021 at 5:51
  • Can you print the contents of data to see whether it contains anything? Anything that is printed should appear in the log file. Commented Sep 30, 2021 at 7:31

2 Answers 2

0

https://docs.python.org/3/library/csv.html

According to the documents, I think you used the wrong way of csv module. So the reader is empty and that's why your code does not return anything

Sign up to request clarification or add additional context in comments.

Comments

0

An easy way to read csv is by using pandas.

import boto3
import pandas as pd

s3 = boto3.client('s3')
response = s3.get_object(Bucket=bucket, Key=path)
content = pd.read_csv(response.get("Body"))

1 Comment

to add pandas for aws lambda need to add a layer, here you can find how to add a layer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.