如何使用Python中的Boto3库使用AWS Resource删除S3中的对象?

如何使用Python中的Boto3库使用AWS Resource删除S3中的对象?

在本文中,我们将看到如何使用Python的Boto 3库从S3中删除对象。

示例 - 从S3的Bucket_1 / testfolder中删除test.zip

更多Python相关文章,请阅读:Python 教程

解决此问题的方法/算法

第1步 - 导入boto3和botocore exceptions以处理异常。

第2步 - s3_files_path是函数的参数。

第3步 - 验证s3_files_path作为s3:// bucket_name / key传递的AWS格式。

第4步 - 使用boto3库创建AWS会话。

第5步 - 为S3创建AWS资源。

第6步 - 拆分S3路径并执行操作以分离根桶名称和要删除的对象路径。

第7步 - 现在,使用函数 delete_object 并传递桶名称和密钥以删除。

第8步 - 对象也是具有文件所有细节的字典。 现在,获取每个文件的 LastModified 详情并与给定的日期时间戳进行比较。

第9步 - 如果删除文件时出现问题,请处理通用异常。

示例

使用以下代码从S3中删除对象 –

import boto3
 from botocore.exceptions import ClientError

 def delete_objects_from_s3(s3_files_path):
     if 's3://' not in s3_files_path:
         raise Exception('给定路径不是有效的s3路径。')
     session = boto3.session.Session(profile_name='saml')
     s3_resource = session.resource('s3')
     s3_tokens = s3_files_path.split('/')
     bucket_name = s3_tokens[2]
     object_path = ""
     filename = s3_tokens[len(s3_tokens) - 1]
     print('bucket_name: ' + bucket_name)

     if len(s3_tokens) > 4:
         for tokn in range(3, len(s3_tokens) - 1):
             object_path += s3_tokens[tokn] + "/"
         object_path += filename
     else:
         object_path += filename
     print('object: ' + object_path)
     try:
         result = s3_resource.meta.client.delete_object(Bucket=bucket_name, Key=object_path)
     except ClientError as e:
         raise Exception("delete_objects_from_s3函数中的boto3客户端错误:" + e.__str__())
     except Exception as e:
         raise Exception("s3 helper的delete_objects_from_s3函数中的意外错误:" + e.__str__())

#删除test.zip
print(delete_objects_from_s3("s3://Bucket_1/testfolder/test.zip")

输出

bucket_name:Bucket_1
object:testfolder/test.zip

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程