This script takes a file from S3 and saves it to a specific path in /tmp .
⚠️ If the file is small (under 5MB), consider reading it into memory using s3.get_object()['Body'].read() instead of writing to disk. This is often faster. lambda download s3 file to tmp
import boto3 import os s3 = boto3.client('s3') def lambda_handler(event, context): # Define bucket and file details bucket_name = 'your-unique-bucket-name' file_key = 'data/report.pdf' # Define the local path in /tmp download_path = '/tmp/local_report.pdf' try: # Download the file s3.download_file(bucket_name, file_key, download_path) # Verify the file exists if os.path.exists(download_path): print(f"File downloaded successfully to {download_path}") # Perform your processing here (e.g., parsing, converting) except Exception as e: print(f"Error: {e}") raise e Use code with caution. 2. Handling Dynamic Filenames This script takes a file from S3 and
file_key = event['Records'][0]['s3']['object']['key'] local_file_name = os.path.basename(file_key) download_path = os.path.join('/tmp', local_file_name) s3.download_file(bucket_name, file_key, download_path) Use code with caution. Best Practices and Limitations import boto3 import os s3 = boto3
Files in /tmp may persist if the Lambda container is reused (a "warm start"). Always clean up files if you are processing sensitive data. Prerequisites To follow this guide, ensure you have: An S3 Bucket with a file to download.
Before writing code, it is important to understand the environment:
No account yet?
Create an Account