使用AWS Lambda和boto3将新行添加到S3中的文本文件对象

时间:2018-06-25 20:40:46

标签: python amazon-s3 aws-lambda boto3

我正在尝试使用python lambda函数在存储在S3中的对象上用换行符添加文本文件。由于存储在S3中的对象是不可变的,因此必须首先将文件下载到'/ tmp /',然后对其进行修改,然后将新版本上传回S3。我的代码附加了数据,但是不会将其添加新行。

BUCKET_NAME = 'mybucket' 
KEY = 'test.txt'
s3 = boto3.resource('s3')

def lambda_handler(event, context):
    try:
        s3.Object(BUCKET_NAME, KEY).download_file('/tmp/test.txt')
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            print("The object does not exist.")
        else:
            raise
    with open('/tmp/test.txt', 'a') as fd:
        fd.write("this is a new string\n")


    s3.meta.client.upload_file('/tmp/test.txt', BUCKET_NAME, KEY)

文件始终附加新的字符串,但永远不附加新的行。有什么想法吗?

更新:在Linux机器或Mac上不会发生此问题。 Lambda函数在linux容器上运行,这意味着/ tmp /中的文件另存为Unix格式的文本文件。某些Windows应用程序不会在Unix格式的文本文件上显示换行符,在这种情况下就是这样。我很笨

2 个答案:

答案 0 :(得分:0)

您需要指定本地文件路径

import boto3
import botocore
from botocore.exceptions import ClientError

BUCKET_NAME = 'mybucket'
KEY = 'test.txt'
LOCAL_FILE = '/tmp/test.txt'
s3 = boto3.resource('s3')

def lambda_handler(event, context):
    try:
        obj=s3.Bucket(BUCKET_NAME).download_file(LOCAL_FILE, KEY)
    except ClientError as e:
        if e.response['Error']['Code'] == "404":
            print("The object does not exist.")
        else:
            raise
    with open('/tmp/test.txt', 'a') as fd:
        fd.write("this is a new string\n")


    s3.meta.client.upload_file(LOCAL_FILE, BUCKET_NAME, KEY)

Boto3文档参考:http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.download_file

答案 1 :(得分:0)

好帖子! 只是一个调整。 您应该在download_file方法的参数中更改LOCAL_FILE和KEY的顺序。 正确的语法是:

obj=s3.Bucket(BUCKET_NAME).download_file(KEY,LOCAL_FILE)

如果在存储桶中找不到文件,我们删除本地文件也很好。因为如果我们不删除本地文件(如果明显存在),我们可能会在已经存在的本地文件中添加新行。 借助此功能:

def remove_local_file(filePath):
import os
     # As file at filePath is deleted now, so we should check if file exists or not not before deleting them
    if os.path.exists(filePath):
        os.remove(filePath)
    else:
        print("Can not delete the file as it doesn't exists")

以“ try”开始的最终代码如下:

try:
    obj=s3.Bucket(BUCKET_NAME).download_file(KEY,LOCAL_FILE)
except ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
        remove_local_file(LOCAL_FILE)
    else:
        raise
with open(LOCAL_FILE, 'a') as fd:
    fd.write("this is a new string\n")

s3.meta.client.upload_file(LOCAL_FILE, BUCKET_NAME, KEY)