Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用AWS Lambda在AWS S3中写入、更新和保存CSV_Python_Csv_Aws Lambda_Csv Write Stream - Fatal编程技术网

Python 如何使用AWS Lambda在AWS S3中写入、更新和保存CSV

Python 如何使用AWS Lambda在AWS S3中写入、更新和保存CSV,python,csv,aws-lambda,csv-write-stream,Python,Csv,Aws Lambda,Csv Write Stream,我正在自动化AWS Textract流程,其中文件通过我已经完成的应用程序上传到S3,一个lambda函数被触发,将表单提取为CSV,并保存在同一个bucket中 我只是用一个Textract公式来计算图像中的所有文本,结果是一个.txt文件。下面是我的代码: def InvokeTextract(bucketName, documentKey): print('Loading InvokeTextract') # Call Amazon Textract respons

我正在自动化AWS Textract流程,其中文件通过我已经完成的应用程序上传到S3,一个lambda函数被触发,将表单提取为CSV,并保存在同一个bucket中

我只是用一个Textract公式来计算图像中的所有文本,结果是一个.txt文件。下面是我的代码:

def InvokeTextract(bucketName, documentKey):
    print('Loading InvokeTextract')
    # Call Amazon Textract
    response = textract.detect_document_text(
        Document={
            'S3Object': {
                'Bucket': bucketName,
                'Name': documentKey
            }
        })

    Textractoutput = ''

    # Print detected text
    for item in response['Blocks']:
        if item['BlockType'] == 'LINE':
            Textractoutput += item['Text'] + '\n'

    return Textractoutput

def writeOutputToS3Bucket(textractData, bucketName, createdS3Document):
    print('Loading writeOutputToS3Bucket')
    generateFilePath = os.path.splitext(createdS3Document)[0] + '.txt'
    s3.put_object(Body=textractData, Bucket=bucketName, Key=generateFilePath)
    print('Generated ' + generateFilePath)


def lambda_handler(event, context):
    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        Textractoutput = InvokeTextract(bucket, key)
        writeOutputToS3Bucket(Textractoutput, bucket, key)

        return 'Processed'
这很好,但是如果我想得到键值对,这是没有帮助的。所以,我尝试使用另一个CSV代码。从我的本地驱动器,我能够做到这一点。以下是我的代码的一部分:

import trp #Local Module
import csv

doc = Document(response) #from TRP

with open('aws_doc.csv', mode='w') as aws_field_file:
    field_write = csv.writer(aws_field_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    field_write.writerow(["Key", "Value"])

    for page in doc.pages:
        for field in page.form.fields:
            # This will write it as your <key>, <value>
            field_write.writerow([field.key, field.value])
但是,当我试图使用Lambda编写代码时,我没有得到结果,即我的bucket中的CSV文件。我读到它,我发现我需要创建一个tmp文件,但这有点不清楚。我使用以下代码:

def lambda_handler(event, context):
    # Get the object from the event and show its content type
    bucketName = event['Records'][0]['s3']['bucket']['name']
    documentKey = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')

    #S3 client
    s3 = boto3.resource('s3')

    # Amazon Textract client
    textract = boto3.client('textract')

    # Get AWS Textract Response for Forms
    response = textract.analyze_document(
        Document={
            'S3Object': {
                'Bucket': bucketName,
                'Name': documentKey
            }
        },
        FeatureTypes = ["FORMS"])

    # Using custom trp module
    doc = Document(response)

    import csv 

    temp_csv_file = csv.writer(open("/tmp/csv_file.csv", "w+"))
    temp_csv_file.writerow(["Key", "Value"])

    for page in doc.pages:
        for field in page.form.fields:
            # This will write it as your <key>, <value>
            temp_csv_file.writerow([field.key, field.value])

    bucketName.upload_file('/tmp/csv_file.csv', 'textractData.csv')
我的代码正确吗?我是不是错过了一步?

而不是

bucketName.upload_file('/tmp/csv_file.csv', 'textractData.csv')
试一试

而不是

bucketName.upload_file('/tmp/csv_file.csv', 'textractData.csv')
试一试


除非需要创建临时文件,否则请尝试此操作

s3.put_objectBody='contents',Bucket='Bucket-name',Key='outputTextFileName'

通过以下方式实现此功能:

def writeCSVcsvData: body=StringIO,因为s3需要字节或类似obj的文件 writer=csv.writerbody 对于csvData中的项目: writer.writerowitem csvS3=body.getvalue 返回csvS3 contents=writeCSV“提供csv数据” s3.put_objectBody=contents,Bucket='Bucket-name',Key='outputTextFileName' S3必须在前面使用S3=boto3定义。客户端'S3' Bucket必须存在于同一个数据库中 关于lambda函数的区域
除非需要创建临时文件,否则请尝试此操作

s3.put_objectBody='contents',Bucket='Bucket-name',Key='outputTextFileName'

通过以下方式实现此功能:

def writeCSVcsvData: body=StringIO,因为s3需要字节或类似obj的文件 writer=csv.writerbody 对于csvData中的项目: writer.writerowitem csvS3=body.getvalue 返回csvS3 contents=writeCSV“提供csv数据” s3.put_objectBody=contents,Bucket='Bucket-name',Key='outputTextFileName' S3必须在前面使用S3=boto3定义。客户端'S3' Bucket必须存在于同一个数据库中 关于lambda函数的区域
我想知道csv文件是否已保存到磁盘。你能把它读出来并打印到控制台上吗?就在bucketName.upload_文件之前,我想知道csv文件是否已保存到磁盘。你能把它读出来并打印到控制台上吗?就在bucketName.upload\u文件之前