繁体   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