TypeError:需要一个类似字节的对象,而不是serverless和Python3的“str”

2024-09-27 04:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个aws lambda函数,每当CSV文件上传到s3bucket时就会触发它。我在python3.6中使用serverless框架,问题是我收到了这个错误消息

a bytes-like object is required, not 'str': TypeError

Traceback (most recent call last):

File "/var/task/handler.py", line 33, in csvfile

fichier = obj['Body'].read().split('\n')

TypeError: a bytes-like object is required, not 'str'

我在net here中做了一些研究,问题是我没有使用open方法,因为文件是由s3事件读取的,所以不知道如何修复它

这是我的代码:

import logging
import boto3
from nvd3 import pieChart
import sys
import csv


xdata = []
ydata = []
xdata1 = []
ydata1 = []


logger = logging.getLogger()
logger.setLevel(logging.INFO)

def csvfile(event, context):

    s3 = boto3.client('s3')    
    # retrieve bucket name and file_key from the S3 event
    bucket_name = event['Records'][0]['s3']['bucket']['name']
    file_key = event['Records'][0]['s3']['object']['key']
    logger.info('Reading {} from {}'.format(file_key, bucket_name))
    # get the object
    obj = s3.get_object(Bucket=bucket_name, Key=file_key)
    # get lines inside the csv
    fichier = obj['Body'].read().split('\n')
    #print lines
     for ligne in fichier:
        if len(ligne) > 1:
            logger.info(ligne.decode())
            liste = ligne.split(',')
            print(liste)
            if liste[2] == 'ByCateg':
                xdata.append(liste[4]) 
                ydata.append(liste[1]) 
            elif liste[2] == 'ByTypes':
                xdata1.append(liste[4]) 
                ydata1.append(liste[1]) 

         print ' '.join(xdata) 

print('Function execution Completed')

这是我的无服务器.yml代码:

^{pr2}$

Tags: keynameimporteventobjobjects3bucket
1条回答
网友
1楼 · 发布于 2024-09-27 04:25:58

问题是

fichier = obj['Body'].read()

返回bytes对象,而不是字符串。这是因为编码可能需要不止一个字符。现在您在一个bytes对象上使用split,但是不能使用字符串拆分它,需要使用另一个bytes对象进行拆分。具体来说

^{pr2}$

在解码之前,也许你应该先修正你的解码错误?在

fichier = obj['Body'].read().decode("utf-8").split('\n')

相关问题 更多 >

    热门问题