AWS Lambdaでs3からcsvファイルを読み込む関数を書いています.
コードはpython 2.7です.
関数の動作段階で、新しく書き込んだファイルを保存する先のパス設定がおかしくなり以下のエラーが出てきてしまいます。
[Errno 2] No such file or directory: u'/read_csv/write.csv'
保存先はread_csv/write.csvのはずなのですが、なぜu'/read_csv/write.csv'で設定されてしまうのでしょうか.PATHの定義の仕方を色々と試したのですが、うまくいかなかったので、ここで質問させていただいてます.
よろしくお願いします.
###該当のソースコード
python2.7
1from __future__ import print_function 2 3#!/usr/bin/env python 4# -*-coding: utf-8 -*- 5# cording:utf-8 6 7import boto3 # aws lambda python module 8import json 9import csv # csv module 10import os 11import re 12import linecache 13# import numpy as np # import numpy module 14 15print('Loading function') 16 17 18# aws s3 information for connection 19s3_client = boto3.client('s3') # .client or .resource 20 21## Event handler------------------------------------------ 22def lambda_handler(event, context): 23 24 # Get uploded file names 25 bucket = event['Records'][0]['s3']['bucket']['name'] # get latest event record happen in s3 bucket 26 key = event['Records'][0]['s3']['object']['key'] # get latest put filename 27 print(bucket) 28 print(key) 29 # obj = bucket.Object(key) # get object 30 31 path_tmp = '/tmp/' + os.path.basename(key) # path to the uploded file (filename) 32 # path_savefile = re.sub('original_csv/', 'read_csv/', key) # replace the file path 33 path_savefile = '/read_csv/' + os.path.basename(key) 34 print(path_tmp) 35 print(path_savefile) 36 37 try: 38 # Download the file from s3 39 s3_client.download_file(Bucket = bucket, Key = key, Filename = path_tmp) 40 41 # readfile and write file to the new csv file 42 43 with open(path_tmp, "r") as f1: # open file for reading 44 with open(path_savefile, "w") as f2: # open file for writing 45 readData = f1.readline() # read lines one by one and delete /n 46 f2.write(readData) # write data to new file 47 48 print('finish create copy') 49 50 # Save the file to s3 51 s3_client.upload_file(Filename = path_savefile, Bucket = bucket, Key = key) 52 print('Succeed in creating a new file') 53 54 except Exception as e: 55 print(e) 56 # raise e
回答2件
あなたの回答
tips
プレビュー