AWS Lambda-Python-在S3中读取打包的zip函数中的csv文件

时间:2019-01-21 06:46:14

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

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

1 个答案:

答案 0 :(得分: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处理代码放入其中并对其执行所需的操作。