为什么从Lambda加载后S3中的csv文件为空 [英] Why the csv file in S3 is empty after loading from Lambda

查看:47
本文介绍了为什么从Lambda加载后S3中的csv文件为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import os
import csv
import boto3

client = boto3.client('s3')

fields = ['dt','dh','key','value']
row = [dt,dh,key,value]
print(row)

# name of csv file 
filename = "/tmp/sns_file.csv"

# writing to csv file 
with open(filename, 'a',newline='') as csvfile: 
    # creating a csv writer object 
    csvwriter = csv.writer(csvfile)

    # writing the fields 
    csvwriter.writerow(fields) 

    # writing the data row
    csvwriter.writerow(row)
    final_file_name="final_report_"+dt+".csv"
    client.upload_file('/tmp/sns_file.csv',BUCKET_NAME,final_file_name)
    if os.path.exists('/tmp/sns_file.csv'):
        os.remove('/tmp/sns_file.csv')
    else:
        print("The file does not exist")

推荐答案

Python的 with 块是上下文管理器,这意味着,简单来说,它将在其中进行所有操作之后清理"完成.

Python's with block is a context manager, which means, in simple terms, it will "clean up" after all operations within it are done.

在文件上下文中,清理"表示关闭文件.除非关闭文件,否则您写入文件的任何更改都不会保存在磁盘上.因此,您需要将上传操作移到 with 块的外部和之后.

In context of files "clean up" means closing file. Any changes you write to the file will not be saved on disk until you close the file. So you need to move upload operation outside and after the with block.

这篇关于为什么从Lambda加载后S3中的csv文件为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆