S3 Functions in Python using Boto
1. Copy from one folder in a bucket to another using Boto. Configure Boto AWS as mentioned in the documentation here
import boto3
import os,sys
bucketName="YOUR BUCKET NAME"
# set this to True if you want the objects in copyToPathDirectory to be deleted first
# set to False if the object being copied has the same name
deleteObjectsFirst = False
# Assuming Boto is setup
s3 = boto3.resource('s3')
s3Client = boto3.client('s3')
bucket = s3.Bucket(bucketName)
copyToPathDirectory = "the/directory/youwant/to/copyto/"
copyFromPathNames = [
"path1/to/copyfrom/",
"path2/to/copyfrom/",
"and/so/on/"
]
# WARNING: This will delete all objects in your folder
# Please check your path before running
if deleteObjectsFirst:
delete_key_list = []
for copyFromPath in copyFromPathNames:
for obj in bucket.objects.filter(Prefix = copyFromPath):
deleteKey = copyToPathDirectory + obj.key
delete_key_list.append({"Key":deleteKey})
if len(delete_key_list) > 100:
s3Client.delete_objects(Bucket=bucketName, Delete={"Objects":delete_key_list})
delete_key_list = []
if len(delete_key_list) > 0:
s3Client.delete_objects(Bucket=bucketName, Delete={"Objects":delete_key_list})
# Copy from one folder to another
for copyFromPath in copyFromPathNames:
for obj in bucket.objects.filter(Prefix = copyFromPath):
copy_source = {'Bucket': bucketName,'Key': obj.key}
toKey = copyToPathDirectory + obj.key
s3.meta.client.copy(copy_source, bucketName, toKey)2. Download files from S3 to local directory
import boto3
import os,sys
bucketName="YOUR BUCKET NAME"
remoteDirectoryName="YOUR DIRECTORY NAME"
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket(bucketName)
for obj in bucket.objects.filter(Prefix = remoteDirectoryName):
if not os.path.exists(os.path.dirname(obj.key)):
os.makedirs(os.path.dirname(obj.key))
bucket.download_file(obj.key, obj.key)
Comments