Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python搜索AWS S3 bucket中的特定文件_Python_Amazon S3_Boto_Boto3_Botocore - Fatal编程技术网

使用python搜索AWS S3 bucket中的特定文件

使用python搜索AWS S3 bucket中的特定文件,python,amazon-s3,boto,boto3,botocore,Python,Amazon S3,Boto,Boto3,Botocore,我有AWS S3访问权限,bucket中有近300个文件。我需要通过模式匹配或搜索从这个bucket下载单个文件,因为我不知道确切的文件名(比如文件以.csv格式结尾)。 下面是我的示例代码,它显示了bucket中的所有文件 def s3connection(credentialsdict): """ :param access_key: Access key for AWS to establish S3 connection :param secret_key: Se

我有AWS S3访问权限,bucket中有近300个文件。我需要通过模式匹配或搜索从这个bucket下载单个文件,因为我不知道确切的文件名(比如文件以.csv格式结尾)。
下面是我的示例代码,它显示了bucket中的所有文件

def s3connection(credentialsdict):
    """
    :param access_key: Access key for AWS to establish S3 connection
    :param secret_key: Secret key for AWS to establish S3 connection
    :param file_name: file name of the billing file(csv file)
    :param bucket_name: Name of the bucket which consists of billing files
    :return: status, billing_bucket, billing_key
    """
    os.environ['S3_USE_SIGV4'] = 'True'
    conn = S3Connection(credentialsdict["access_key"], credentialsdict["secret_key"], host='s3.amazonaws.com')
    billing_bucket = conn.get_bucket(credentialsdict["bucket_name"], validate=False)
    try:
        billing_bucket.get_location()
    except S3ResponseError as e:
        if e.status == 400 and e.error_code == 'AuthorizationHeaderMalformed':
            conn.auth_region_name = ET.fromstring(e.body).find('./Region').text
    billing_bucket = conn.get_bucket(credentialsdict["bucket_name"])
    print billing_bucket

    if not billing_bucket:
        raise Exception("Please Enter valid bucket name. Bucket %s does not exist"
                        % credentialsdict.get("bucket_name"))
    for key in billing_bucket.list():
        print key.name
    del os.environ['S3_USE_SIGV4']

我可以传递搜索字符串来检索完全匹配的文件名吗?

没有办法这样做,因为S3中没有对
regex
的本机支持。您必须获取整个列表,并在客户端应用search/regex。
列表对象
中唯一可用的过滤选项是通过
前缀

前缀(字符串)——将响应限制为以 指定的前缀

一个选项是使用Python模块
re
,并将其应用于对象列表

import re
pattern = re.compile(<file_pattern_you_are_looking_for>)
for key in billing_bucket.list():
    if pattern.match(key.name):
        print key.name
重新导入
pattern=re.compile()
对于账单中的键,请参见bucket.list():
如果pattern.match(key.name):
打印key.name

您也可以使用简单的if条件

prefix_objs = buck.objects.filter(Prefix="your_bucket_path")

for obj in prefix_objs:
    key = obj.key
    if key.endswith(".csv"):
        body = obj.get()['Body'].read()
        print(obj.key)

您可以使用JMESPath表达式来搜索和筛选S3文件。为此,您需要将s3分页器置于
列出对象\u v2
之上

import boto3
client = boto3.client('s3')
paginator = client.get_paginator('list_objects_v2')
page_iterator = paginator.paginate(Bucket="your_bucket_name")
既然您有了迭代器,就可以使用JMESPath搜索了。 最有用的是-to-do
%like%
查询

objects = page_iterator.search("Contents[?contains(Key, `partial-file-name`)][]")
objects = page_iterator.search("Contents[?ends_with(Key, `.csv`)][]")
但在您的情况下(要查找所有以
.csv
结尾的文件,最好使用-to do
*.csv
查询

objects = page_iterator.search("Contents[?contains(Key, `partial-file-name`)][]")
objects = page_iterator.search("Contents[?ends_with(Key, `.csv`)][]")
然后,您可以使用

for item in objects:
    print(item['Key'])
这个答案基于和