Let’s look at a script that downloads a CSV file named reports/2023_data.csv from a bucket called my-company-data and saves it locally as annual_report.csv .
: Ensure your environment variables ( AWS_ACCESS_KEY_ID , AWS_SECRET_ACCESS_KEY ) are set or your ~/.aws/credentials file is configured. s3.download_file example
import boto3 from botocore.exceptions import NoCredentialsError, ClientError def download_s3_file(bucket_name, s3_object_key, local_file_path): s3 = boto3.client('s3') try: print(f"Attempting to download {s3_object_key}...") s3.download_file(bucket_name, s3_object_key, local_file_path) print(f"Success! File saved to {local_file_path}") except NoCredentialsError: print("Error: AWS credentials not found.") except ClientError as e: if e.response['Error']['Code'] == "404": print("Error: The object does not exist.") else: print(f"An error occurred: {e}") # Usage download_s3_file('my-company-data', 'reports/2023_data.csv', 'annual_report.csv') Use code with caution. Advanced Options: Using TransferConfig Let’s look at a script that downloads a
from boto3.s3.transfer import TransferConfig config = TransferConfig( multipart_threshold=1024 * 25, # 25MB max_concurrency=10, # Number of threads use_threads=True ) s3.download_file( 'my-bucket', 'large_video.mp4', 'local_video.mp4', Config=config ) Use code with caution. download_file vs. download_fileobj download_fileobj It’s easy to get these two mixed up
It’s easy to get these two mixed up. Here is the simple rule:
In this guide, we’ll break down exactly how to use s3.download_file with clear examples. What is s3.download_file ?