我正在使用 python3 中的 ListObjectsV2 檢查 s3 位置是否存在。
我有需要驗證 s3 物件的檔案型別或擴展名的用例。
import boto3
s3 = boto3.client("s3")
bucket="bucketName"
key="folder1/folder2/myObject.csv"
res = s3.list_objects_v2(Bucket=bucket, Prefix=key)
print(res)
print(res.get("KeyCount"))
if res.get("KeyCount") > 0: print("s3 object exists")
else: print("s3 object does not exists")
示例物件如下:s3://bucketName/folder1/folder2/myObject.csv
以下這些場景給出了輸出:
- s3://bucketName/folder1/folder2/myObject.csv 給出“s3 物件存在”
- s3://bucketName/folder1/folder2/myObject.c 給出“s3 物件存在”
- s3://bucketName/folder1/folder2/myObject. 給出“s3物件存在”
- s3://bucketName/folder1/folder2/myObject.x 給出“s3 物件不存在”
我正在觀察部分擴展也在驗證中。
我想要 2,3 也因為“s3 物件不存在”。我可能有很多擴展名,所以不能使用“ends with”。也許我可以嘗試使用決議器在“.”之后分割 s3path。用于擴展和使用結束。但我正在尋找更簡單的方法。
提前致謝。
uj5u.com熱心網友回復:
" ListObject "限制對以指定前綴開頭的鍵的回應。這正是您所看到的,因為“folder1/folder2/myObject.csv”以“folder1/folder2/myObject”開頭。
如果要查看物件是否存在,則需要對特定物件進行操作的 API。一種這樣的選擇是呼叫HeadObject并查看它是否因無效鍵而失敗:
import botocore.exceptions
def does_key_exist(s3, bucket, key):
try:
# Try to head the object
s3.head_object(Bucket=bucket, Key=key)
# All good
return True
except botocore.exceptions.ClientError as e:
# See if the failure is because the object doesn't exist
code = e.response['Error']['Code']
if code == "NoSuchKey" or code == "404":
return False
else:
# Some other error, let the caller handle it if they want
raise
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/354351.html
標籤:亚马逊网络服务 亚马逊-s3 boto3 python-3.8
上一篇:秘密值無法轉換為鍵名和值對
