【问题标题】:Get only file names from s3 bucket folder仅从 s3 存储桶文件夹中获取文件名
【发布时间】:2020-04-01 04:51:37
【问题描述】:

我有一个名为“Sample_Bucket”的 s3 存储桶,其中有一个名为“Sample_Folder”的文件夹。我只需要获取“Sample_Folder”文件夹中所有文件的名称。

我正在使用以下代码来执行此操作 -

import boto3
s3 = boto3.resource('s3', region_name='us-east-1', verify=False)
    bucket = s3.Bucket('Sample_Bucket')
    for files in bucket.objects.filter(Prefix='Sample_Folder):
        print(files)

变量文件包含以文件名为键的对象变量。

s3.ObjectSummary(bucket_name='Sample-Bucket', key='Sample_Folder/Sample_File.txt')

但我只需要文件名。 我该如何提取它?或者有没有其他方法可以做到?

【问题讨论】:

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


【解决方案1】:

给你。

import boto3


bucket = "Sample_Bucket"
folder = "Sample_Folder"
s3 = boto3.resource("s3")
s3_bucket = s3.Bucket(bucket)
files_in_s3 = [f.key.split(folder + "/")[1] for f in s3_bucket.objects.filter(Prefix=folder).all()]

【讨论】:

  • 谢谢。我喜欢尽可能使用 boto3.resource。
【解决方案2】:

您应该使用 list_object_v2,它会根据使用的已定义前缀为您提供列表。

... snippet ...

filenames = []

get_filenames(s3):
    result = s3.list_objects_v2(Bucket=bucket, Prefix=prefix)
    for item in result['Contents']:
        files = item['Key']
        print(files)
        filenames.append(files)   #optional if you have more filefolders to got through.
    return filenames

get_filenames(my_bucketfolder)

【讨论】:

  • 最多可以获得 1000 个对象。令人难以置信的是,他们硬编码了这个限制,而你无法更改。
【解决方案3】:

对于我自己,我做了一个你可能会觉得有用的函数:

import boto3


s3_client = boto3.client('s3')


def list_objects_without_response_metadata(**kwargs):
    ContinuationToken = None
    while True:
        if ContinuationToken:
            kwargs["ContinuationToken"] = ContinuationToken
        res = s3_client.list_objects_v2(**kwargs)
        for obj in res["Contents"]:
            yield obj
        ContinuationToken = res.get("NextContinuationToken", None)
        if not ContinuationToken:
            break


file_names = [obj["Key"] for obj in list_objects_without_response_metadata(Bucket='Sample_Bucket', Prefix='Sample_Folder')]

【讨论】:

    【解决方案4】:

    如果您不想使用boto3.client 而更喜欢boto3.resource,您可以使用此sn-p 列出目录中的所有目录名称。

    import boto3
    
    s3 = boto3.resource('s3')
    bucket = s3.Bucket("Sample_Bucket")
    res = bucket.meta.client.list_objects(Bucket=bucket.name, Delimiter='/', Prefix = "Sample_Folder/"')
    for o in res.get('CommonPrefixes'):
        print(o.get('Prefix'))
    

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 2021-07-03
      • 1970-01-01
      • 2015-05-20
      • 2016-06-22
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多