【问题标题】:AWS Lambda - Python - reading csv file in S3-uploaded packaged zip functionAWS Lambda - Python - 在 S3 上传的打包 zip 函数中读取 csv 文件
【发布时间】:2019-01-22 11:53:32
【问题描述】:

我在 Python 3.6 中有一个 lambda 函数,我将其压缩成一个 zip 文件以上传到 S3(函数文件夹总大小为 180MB,这就是原因)。在 zip 中,我有 1 个 csv 文件('example.csv'),我想在 lambda 处理程序函数中读取它。

如何读取这个文件? 我试过了:

filename = 'example.csv'
filepath = os.environ['LAMBDA_TASK_ROOT'] + '/' + filename
df = pd.read_csv(filepath, dtype=str)

# Failed with OSError: Initializing from file failed

我的 lambda 函数文件夹内容示例:

root:
 -- lambda_function.py
 -- example.csv
 -- bunch of library folders

我的 csv 文件的内容:

  id | value | something | else
-----------------------------------
  0  |  lol  |    ok     |  bye
  1  |  omg  |    foo    |  bar
  2  |  thx  |    baz    |  qux

我的 csv 文件的路径是什么?

【问题讨论】:

  • 可以在/tmp/文件夹下下载。
  • 我该怎么做呢? csv 文件在 zip 包中。
  • 请看贴出的答案

标签: python amazon-web-services aws-lambda


【解决方案1】:

我假设您使用的是boto3,在文档中有download_file 方法可用于在本地下载文件。

import boto3
import zipfile
def lambda_handler(event, context):
    s3 = boto3.resource('s3')
    s3.Bucket('<first_bucket>').download_file('<file_name>.zip', '/tmp/<file_name>.zip')

    # put unzip code
    zip_ref = zipfile.ZipFile('/tmp/<file_name>.zip', 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()
    #handle CSV file reading and rest of operation

在上述代码之后,您可以将您的csv处理代码读取并对其执行所需的操作。

【讨论】:

  • 我不认为,你可以直接解压s3桶文件,然后在本地下载。
猜你喜欢
  • 2018-09-13
  • 2017-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多