【问题标题】:AWS S3 check if file exists based on a conditional pathAWS S3 根据条件路径检查文件是否存在
【发布时间】:2019-10-15 08:27:35
【问题描述】:

如果给定文件存在,我想检查文件是否存在于存储桶的单独目录中。我有以下目录结构-

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 作为参数。有没有更好更优雅的方法呢?

基本上我必须检查是否,

my-bucket/folder1/folder2/test.jpg 如果存在则检查 my-bucket/folder1/&lt;randomID&gt;/test_condition.jpg如果也存在则返回True

【问题讨论】:

  • 你是说你想找bucket/folder1/*/test_condition.jpg吗?也就是说,在“任何”文件夹中查找对象?
  • @JohnRotenstein 是的,正确的。

标签: python-3.x amazon-web-services amazon-s3


【解决方案1】:

我最终使用了这个,它给出了更简洁的代码

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")

【讨论】:

    【解决方案2】:

    无法通过通配符指定对象键。

    相反,您需要创建一个存储桶列表(可以针对整个存储桶,也可以在一个路径中),然后执行您自己的逻辑来识别感兴趣的文件。

    如果对象的数量很少(例如几千个),则可以轻松检索列表并将其保存在内存中,以便在 Python 列表中进行快速比较。

    如果有数百万个对象,您可以考虑使用Amazon S3 Inventory,它可以提供一个每日 CSV 文件,列出存储桶中的所有对象。使用这样的文件会比扫描存储桶本身更快。

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多