【问题标题】:Write csv file and save it into S3 using AWS Lambda (python)使用 AWS Lambda (python) 编写 csv 文件并将其保存到 S3
【发布时间】:2018-09-16 14:46:03
【问题描述】:

我正在尝试使用 AWS Lambda 将 csv 文件写入 S3 存储桶,为此我使用了以下代码:

data=[[1,2,3],[23,56,98]]
with open("s3://my_bucket/my_file.csv", "w") as f:
   f.write(data)

这会引发以下错误:

[Errno 2] No such file or directory: u's3://my_bucket/my_file.csv': IOError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 51, in lambda_handler
with open("s3://my_bucket/my_file.csv", "w") as f:
IOError: [Errno 2] No such file or directory: u's3://my_bucket/my_file.csv'

请问我可以帮忙吗?

PS:我使用的是 python 2.7

提前谢谢你

【问题讨论】:

  • Lambda 没有像这样的 s3:// URI 的本机设备驱动程序支持。将 CSV 文件写入本地文件系统 (/tmp),然后使用 boto3 的 put_object() 方法。如果愿意,您还可以使用 boto3 将文件内容流式传输到 S3。
  • @jarmod 你能举个例子吗,非常感谢

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


【解决方案1】:

晚点回答总比不回答好。在 S3 中获取数据有四个步骤:

  • 调用 S3 存储桶
  • 使用 requests 库将数据加载到 Lambda 中(如果您没有安装,则必须将其作为层加载)
  • 将数据写入 Lambda '/tmp' 文件
  • 上传文件到s3

类似这样的:

import csv
import requests
#all other apropriate libs already be loaded in lambda

#properly call your s3 bucket
s3 = boto3.resource('s3')
bucket = s3.Bucket('your-bucket-name')
key = 'yourfilename.txt'

#you would need to grab the file from somewhere. Use this incomplete line below to get started:
with requests.Session() as s:
    getfile = s.get('yourfilelocation')

#Only then you can write the data into the '/tmp' folder.
with open('/tmp/yourfilename.txt', 'w', newline='') as f:
    w = csv.writer(f)
    w.writerows(filelist)
#upload the data into s3
bucket.upload_file('/tmp/yourfilename.txt', key)

希望对你有帮助。

【讨论】:

    【解决方案2】:

    我不知道使用 AWS Lambda,但我一直在使用 Boto3 来做同样的事情。 这是一个简单的几行代码。

    #Your file path will be something like this:
    #s3://<your_s3_bucket_name>/<Directory_name>/<File_name>.csv
    
    import boto3
    
    BUCKET_NAME = '<your_s3_bucket_name>'
    PREFIX = '<Directory_name>/'
    s3 = boto3.resource('s3')
    obj = s3.Object(BUCKET_NAME, PREFIX + '<File_name>.csv')
    obj.put(Body=content)
    

    【讨论】:

      【解决方案3】:
      with open("s3://my_bucket/my_file.csv", "w+") as f:
      

      而不是

      with open("s3://my_bucket/my_file.csv", "w") as f:
      

      注意“w”已更改为“w+”,这意味着它将写入文件,如果它不存在,它将创建它。

      【讨论】:

      • 好的,s3://my_bucket/ 目录真的存在吗?
      • 是但文件不存在
      • s3://my_bucket/“目录”在本地不存在......它在 S3 上。它甚至不是一个目录,它是一个 S3 存储桶。不能像本地文件一样访问,必须使用boto3。
      猜你喜欢
      • 2020-12-28
      • 2018-12-15
      • 2016-11-03
      • 2018-06-08
      • 2020-02-06
      • 2021-04-18
      • 2018-08-03
      • 1970-01-01
      • 2021-01-31
      相关资源
      最近更新 更多