Aakash Sharma
Aakash Sharma

Reputation: 67

Error in AWS Lambda function while reading from S3

I am trying to read an excel file from S3 bucket. Here is my Lambda function code but it throws syntax error for any statement after I read the byte stream into a dataframe using pd.read_excel.

I am unable to figure out the issue as syntax looks fine to me. Is there an issue with reading the data? Kindly help.

import json
import boto3
import pandas as pd
import io


def lambda_handler(event, context):
    
    s3 = boto3.client("s3")
    s3_resource = boto3.resource("s3")
    
    if event:
        
        s3_records = event["Records"][0]
        bucket_name = str(s3_records["s3"]["bucket"]["name"])
        file_name = str(s3_records["s3"]["object"]["key"])
        
        file_obj = s3.get_object(Bucket=bucket_name, Key=file_name)
        file_content = file_obj["Body"].read()
        
        df = pd.read_excel(io.BytesIO(file_content, engine='xlrd')
          
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

Here is the log:

[ERROR] Runtime.UserCodeSyntaxError: Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 23)
Traceback (most recent call last):
  File "/var/task/lambda_function.py" Line 23
        return {

Upvotes: 0

Views: 531

Answers (1)

Leo von Barbarosa
Leo von Barbarosa

Reputation: 765

It seems you're missing closing parenthesis just before the return statement, it should be this:

df = pd.read_excel(io.BytesIO(file_content, engine='xlrd'))

instead of this

df = pd.read_excel(io.BytesIO(file_content, engine='xlrd')

Upvotes: 2

Related Questions