1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【python】S3上のcsvファイルから、dynamoDBにデータをインポートするAWS lambdaのサンプルコード

Last updated at Posted at 2022-05-18

こちらでスプレッドシートをcsvに変換してS3に保存したので、csvからdynamoDBのテーブルを作成しました。

サンプルコード

import os
import boto3
import pandas as pd

s3_client = boto3.client("s3")
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("任意のテーブル名")


def lambda_handler(event, context):
    bucket_name = os.environ['bucket_name']
    prefix = os.environ['prefix']

    s3 = boto3.client('s3')
    obj = s3.get_object(Bucket=bucket_name, Key=prefix)
    df = pd.read_csv(obj['Body'], dtype='object')

    for index, item in df.iterrows():
        try:
            table.put_item(
                Item = {
                    "foo"  : str(item['foo']),
                    "bar"  : str(item['bar']),
                    "baz"  : str(item['baz'])
                }
            )
        except Exception as e:
            print(e)

※ 実行するたびにテーブルが上書きされます

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?