python - 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 文件的路径是什么?
解决方案
我假设您使用的是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 处理代码读取并对其执行所需的操作。
推荐阅读
- scope - 使用 Jupyter 单元魔法时的环境变量范围
- c# - unity3D ScrollView 动态宽度
- pandas - relativedelta - 根据列值添加月数
- php - 无法获得中间件授权工作
- android - 如何使用上一个和下一个按钮切换片段?
- java - 使用 IText 或 PDFBox 在 java 中的另一个 PDF 文件之间合并 PDF 文件
- c++ - 从在线服务器上的计算机上传文件
- java - 使用 post 方法后信息不会出现在其他页面中
- google-apps-script - 只修改主题并发送草稿
- python - 为什么在使用 tensorflow 对象检测 api 重新训练预训练模型时以这种方式标记训练数据会导致错误的对象检测?