how to read the csv file using pandas in aws lambda code example
Example 1: how to read the csv file using pandas in aws lambda
import json
import os
import boto3
import csv
import sys
import pandas as pd
from io import BytesIO
s3_client = boto3.client('s3')
bucket_name ='bucket_name'
s3_file_name ='s3_file_name.csv'
def lambda_handler(event, context):
print(event)
try:
resp = s3_client.get_object(Bucket=bucket_name, Key=s3_file_name)
df= pd.read_csv(resp['Body'], sep=',')
print(df.head(2))
except Exception as err:
print(err)
Example 2: read csv file in aws lambda python
import json
import os
import boto3
import csv
key ='file_name.csv'
bucket ='bucket_name'
def lambda_handler(event, context):
s3_resource = boto3.resource('s3')
s3_object = s3_resource.Object(bucket, key)
data = s3_object.get()['Body'].read().decode('utf-8').splitlines()
lines = csv.reader(data)
headers = next(lines)
print('headers: %s' %(headers))
for line in lines:
print(line)
print(line[0], line[1])