March 15, 2017

How to upload files to S3 using Python Boto3?

The below script gives you a quick example of uploading a specific file to the S3 bucket, provided the IAM user calling the API has the s3:GetObject permissions on the S3 bucket.

# Boto3 script to upload a file to S3
import boto3
session = boto3.Session(profile_name='<profilename>') #ensure to use appropriate  profile
s3_client = session.client('s3')

print "Upload the your test file to S3"
s3_client.upload_file('<file path>/<file name with extension>', '<s3 bucket name>', '<prefixfolder/filename with extension>)

print "Success! Upload complete"
print "Getting list"
files=s3_client.list_objects(Bucket='<s3 bucket name>', Prefix='<prefixfolder/filename with extension>')['Contents']

for key in files:

   print key