簡體   English   中英

如何從 AWS Lambda 中的 s3 存儲桶讀取 csv 文件?

[英]How to read csv file from s3 bucket in AWS Lambda?

我正在嘗試讀取上傳到 s3 存儲桶上的 csv 文件的內容。 為此,我從觸發 lambda 函數的事件中獲取存儲桶名稱和文件鍵,並逐行讀取。 這是我的代碼:

import json
import os
import boto3
import csv

def lambda_handler(event,  context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        file_key = record['s3']['object']['key']
        s3 = boto3.client('s3')
        csvfile = s3.get_object(Bucket=bucket, Key=file_key)
        csvcontent = csvfile['Body'].read().split(b'\n')
        data = []
        with open(csvfile['Body'], 'r') as csv_file:
          csv_file = csv.DictReader(csv_file)
          data = list(csv_file)

我在 CloudWatch 上遇到的確切錯誤是:

[ERROR] TypeError: expected str, bytes or os.PathLike object, not list
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 19, in lambda_handler
    with open(csvcontent, 'r') as csv_file:

有人可以幫我解決這個問題嗎? 感謝您提供的任何幫助,因為我是 lambda 的新手

要以正確且易於檢索的索引格式從 s3 存儲桶中獲取 CSV 文件數據,下面的代碼對我有很大幫助:

key = 'key-name'
bucket = 'bucket-name'
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 complete line
    print(line)
    #print index wise
    print(line[0], line[1])
csvfile = s3.get_object(Bucket=bucket, Key=file_key)
csvcontent = csvfile['Body'].read().split(b'\n')

在這里,您已經檢索了文件內容並將其拆分為多行。 我不確定您為什么要再次open某些內容,您可以將csvcontent傳遞給您的閱讀器:

csv_data = csv.DictReader(csvcontent)

csvfile['Body']類型是StreamingBody ,因此您不能使用open xx with .

此代碼已從流中讀取所有數據。

csvcontent = csvfile['Body'].read().split(b'\n')

所以只需解析該行以獲得更有用的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM