3

My development environment is a Windows machine. When trying to download a file from S3 locally it works no problem. When I load the function to Lambda, however, I receive a FileNotFoundError error which is caused by the Lambda requiring a leading slash in the file key.

This works locally, but does not on Lambda...

s3 = boto3.resource('s3')
new_file_key = os.path.join('tmp', file_name)
s3.Bucket('bucketname').download_file(file_key, new_file_key)

This works on Lambda, but not locally...

s3 = boto3.resource('s3')
new_file_key = os.path.join('/tmp', file_name)
s3.Bucket('bucketname').download_file(file_key, new_file_key)

What's the simplest way to handle this?

1
  • Where is the value of file_name coming from? Mar 25, 2018 at 17:00

2 Answers 2

5

It sounds like you want the file to be downloaded to

  • C:\tmp on windows
  • /tmp on your lambda container (linux)

Using this SO answer as a reference, the following should behave in a platform-agnostic manner:

s3 = boto3.resource('s3')
new_file_key = os.path.abspath(os.path.join(os.sep, 'tmp', file_name))
s3.Bucket('bucketname').download_file(file_key, new_file_key)
0
0

On MS Windows os.path.join uses \ which doesn't work with s3 paths

The Lambda is running on a Linux host so os.path.join is / which s3 likes

To fix it hardwire the join to use /

new_file_key = '/'.join(['/tmp', file_name])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.