I did this to move files between 2 S3 locations.
It handles the following scenario :
- If you want to move files with specific prefixes in their names
- If you want to move them between 2 subfolders within the same bucket
- If you want to move them between 2 buckets
import boto3
s3 = boto3.resource('s3')
vBucketName = 'xyz-data-store'
#Source and Target Bucket Instantiation
vTargetBkt = s3.Bucket('xyz-data-store')
vSourceBkt = s3.Bucket('xyz-data-store')
#List of File name prefixes you want to move
vSourcePath = ['abc/1/test1_', 'abc/1/test2_'
,'abc/1/test3_','abc/1/test4_']
#List of Folder names you want the files to be moved to
vTargetPath = ['abc/1/test1_', 'abc/1/test2_'
,'abc/1/test3_','abc/1/test4_']
for (sP, tP) in zip(vSourcePath,vTargetPath) :
for se_files in vSourceBkt.objects.filter(Prefix = sP, Delimiter = '/'):
SourceFileName = (se_files.key).split('/')[-1]
copy_source = {
'Bucket': vSourceBkt.name,
'Key': se_files.key
}
#print('SourceFileName ' + SourceFileName)
#print('se_files ' + se_files.key)
TargetFileName = str("{}{}".format(tP,SourceFileName))
print('TargetFileName ' + TargetFileName)
s3.meta.client.copy(copy_source, vBucketName, TargetFileName)
#Delete files in the Source when the code is working