![](/img/trans.png)
[英]Move all files in s3 bucket from s3 account to another using boto3
[英]Is there a way to move all files with specific file extensions from one folder to another in S3 using Boto3 python?
我正在尝试使用 S3 API 将特定文件扩展名的所有文件从一个文件夹移动到另一个文件夹。
我用来移动文件的代码是:
s3_resource = boto3.resource(‘s3’)
s3_resource.Object(“bucket_name”, “newpath/to/object_B.txt”).copy_from(
CopySource=”path/to/your/object_A.txt”)
s3_resource.Object(“bucket_name”, “path/to/your/object_A.txt”).delete()
有没有办法修改它以仅移动具有特定扩展名的文件(例如.txt
和.csv
)?
它会是这样的:
import boto3
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket('bucket-name')
for object in bucket.objects.filter(Prefix='source_path/'):
if object.key.endswith('.txt') or object.key.endswith('.csv'):
bucket.Object(...).copy(...)
object.delete(...)
您将需要修改目标键以包含目标路径。
使用了@John 的一些代码
import boto3
import json
def lambda_handler(event, context):
s3 = boto3.resource('s3')
src_bucket = s3.Bucket('mybucket-test-all-files')
dest_bucket_jpg = s3.Bucket('mybucket-test-jpg-files')
dest_bucket_png = s3.Bucket('mybucket-test-png-files')
for object in src_bucket.objects.all():
if object.key.endswith('.jpg') or object.key.endswith('.jpeg'):
copy_source = {
'Bucket': src_bucket,
'Key': object.key
}
dest_bucket_jpg.copy(copy_source, object.key)
object.delete()
elif object.key.endswith('.png'):
copy_source = {
'Bucket': src_bucket,
'Key': object.key
}
dest_bucket_png.copy(copy_source, object.key)
object.delete()
else:
print("Not copying any objects with diff file-types")
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Files Copied Successfully')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.