首页 > 解决方案 > AWS Lambda - Python - 在 S3 上传的打包 zip 函数中读取 csv 文件

问题描述

我在 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 文件的路径是什么?

标签: pythonamazon-web-servicesaws-lambda

解决方案


我假设您使用的是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 处理代码读取并对其执行所需的操作。


推荐阅读