如何使用 Python 中的 Boto3 庫透過 AWS 資源從 S3 刪除物件?


在本文中,我們將瞭解如何使用 Python 的 Boto 3 庫從 S3 刪除物件。

示例 - 從 S3 的 Bucket_1/testfolder 中刪除 test.zip

解決此問題的方法/演算法

步驟 1 - 匯入 boto3 和 botocore 異常以處理異常。

步驟 2 - s3_files_path 是函式中的引數。

步驟 3 - 驗證 s3_files_path 是否以 AWS 格式(例如 s3://bucket_name/key)傳遞。

步驟 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('Given path is not a valid s3 path.')
   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( "boto3 client error in delete_objects_from_s3 function: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in delete_objects_from_s3 function of s3 helper: " + e.__str__())

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

輸出

bucket_name: Bucket_1
object: testfolder/test.zip

更新於: 2021年3月22日

1K+ 閱讀量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告