AWS S3根据条件路径检查文件是否存在 [英] AWS S3 check if file exists based on a conditional path
问题描述
如果给定文件存在,我想检查文件是否存在于存储桶的单独目录中.我具有以下目录结构-
I would like to check if a file exists in a separate directory of the bucket if a given file exists. I have the following directory structure-
import boto3
s3 = boto3.resource('s3')
def file_exists(fileN):
try:
s3.Object('my-bucket', 'folder1/folder2/'+fileN).load()
except:
return False
else:
fileN = fileN.split(".")[0]
try:
s3.Object('my-bucket', 'folder1/<randomid folderxxxx>/'+fileN+'_condition.jpg').load()
except:
return False
else:
return True
file_exists("test.jpg")
这可行,但是只要我可以发送 randomfolderID
作为参数即可.有没有更好,更优雅的方法呢?
This works but as long as I can send the randomfolderID
as an argument. Is there a better and elegant way to do it?
基本上我必须检查一下,
Basically I have to check if,
my-bucket/folder1/folder2/test.jpg
(如果存在),然后检查 my-bucket/folder1/< randomID>/test_condition.jpg
(如果还存在),则返回 True
my-bucket/folder1/folder2/test.jpg
if this exists then check
my-bucket/folder1/<randomID>/test_condition.jpg
if this also exists then return True
推荐答案
我最终使用了这个代码,它提供了一些简洁的代码
I ended up using this which gave a little cleaner code
import boto3
s3client = boto3.client('s3')
def all_file_exist(bucket, prefix, fileN):
fileFound = False
fileConditionFound = False
theObjs = s3client.list_objects_v2(Bucket=bucket, Prefix=prefix)
for object in theObjs['Contents']:
if object['Key'].endswith(fileN+'_condition.jpg') :
fileConditionFound = True
if object['Key'].endswith(fileN+".jpg") :
fileFound = True
if (fileFound and fileConditionFound) :
return True
return False
all_file_exist("bucket","folder1", "test")
这篇关于AWS S3根据条件路径检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!