我想知道boto3中是否存在一个键。我可以循环桶内容并检查键是否匹配。
但这似乎太长了,也太过分了。Boto3官方文档明确说明了如何做到这一点。
也许我忽略了最明显的一点。有人能告诉我怎么做吗?
我想知道boto3中是否存在一个键。我可以循环桶内容并检查键是否匹配。
但这似乎太长了,也太过分了。Boto3官方文档明确说明了如何做到这一点。
也许我忽略了最明显的一点。有人能告诉我怎么做吗?
当前回答
您可以使用awswrangler在一行中完成它。
awswrangler.s3.does_object_exist(path_of_object_to_check)
https://aws-data-wrangler.readthedocs.io/en/stable/stubs/awswrangler.s3.does_object_exist.html
does_object_exist方法使用s3客户机的head_object方法并检查是否引发了ClientError。如果错误代码是404,则返回False。
其他回答
试试这个简单的方法
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket_name') # just Bucket name
file_name = 'A/B/filename.txt' # full file path
obj = list(bucket.objects.filter(Prefix=file_name))
if len(obj) > 0:
print("Exists")
else:
print("Not Exists")
您可以使用awswrangler在一行中完成它。
awswrangler.s3.does_object_exist(path_of_object_to_check)
https://aws-data-wrangler.readthedocs.io/en/stable/stubs/awswrangler.s3.does_object_exist.html
does_object_exist方法使用s3客户机的head_object方法并检查是否引发了ClientError。如果错误代码是404,则返回False。
这里有一个对我有用的解决办法。需要注意的是,我事先知道密钥的确切格式,所以我只列出单个文件
import boto3
# The s3 base class to interact with S3
class S3(object):
def __init__(self):
self.s3_client = boto3.client('s3')
def check_if_object_exists(self, s3_bucket, s3_key):
response = self.s3_client.list_objects(
Bucket = s3_bucket,
Prefix = s3_key
)
if 'ETag' in str(response):
return True
else:
return False
if __name__ == '__main__':
s3 = S3()
if s3.check_if_object_exists(bucket, key):
print "Found S3 object."
else:
print "No object found."
不仅是客户端,还有桶:
import boto3
import botocore
bucket = boto3.resource('s3', region_name='eu-west-1').Bucket('my-bucket')
try:
bucket.Object('my-file').get()
except botocore.exceptions.ClientError as ex:
if ex.response['Error']['Code'] == 'NoSuchKey':
print('NoSuchKey')
Boto 2的Boto。s3.key。Key对象曾经有一个exists方法,通过执行HEAD请求并查看结果来检查Key是否存在于S3上,但它似乎已经不存在了。你必须自己动手:
import boto3
import botocore
s3 = boto3.resource('s3')
try:
s3.Object('my-bucket', 'dootdoot.jpg').load()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
# The object does not exist.
...
else:
# Something else has gone wrong.
raise
else:
# The object does exist.
...
load()对单个键执行HEAD请求,这是快速的,即使有问题的对象很大,或者bucket中有很多对象。
当然,您可能会检查对象是否存在,因为您计划使用它。如果是这种情况,您可以忘记load(),直接执行get()或download_file(),然后在那里处理错误情况。