【问题标题】:How can I get ONLY files from S3 with python aioboto3 or boto3?如何使用 python aioboto3 或 boto3 仅从 S3 获取文件?
【发布时间】:2021-10-15 04:09:17
【问题描述】:

我有这段代码,我只想要以没有中间空文件夹的文件结尾的路径。例如:

data/folder1/folder2
data/folder1/folder3/folder4/file1.txt
data/folder5/file2.txt

从那些我只想要的路径:

data/folder1/folder3/folder4/file1.txt
data/folder5/file2.txt

我正在使用此代码,但它也为我提供了以目录结尾的路径:

    subfolders = set()
    current_path = None

    result = await self.s3_client.list_objects(Bucket=bucket, Prefix=prefix)
    objects = result.get("Contents")

    try:
        for obj in objects:
            current_path = os.path.dirname(obj["Key"])
            if current_path not in subfolders:
                subfolders.add(current_path)
    except Exception as exc:
        print(f"Getting objects with prefix: {prefix} failed")
        raise exc

【问题讨论】:

标签: python amazon-s3 boto3


【解决方案1】:

我建议在这里使用 boto3 Bucket 资源,因为它简化了分页。

以下是如何获取 S3 存储桶中所有文件列表的示例:

import boto3

bucket = boto3.resource("s3").Bucket("mybucket")
objects = bucket.objects.all()

files = [obj.key for obj in objects if not obj.key.endswith("/")]
print("Files:", files)

值得注意的是,获取 S3 存储桶中所有文件夹和子文件夹的列表是一个更难解决的问题,主要是因为文件夹通常不存在于 S3 中。它们在逻辑上存在,但在物理上不存在,因为存在具有给定分层键的对象,例如dogs/small/corgi.png。有关想法,请参阅retrieving subfolder names in S3 bucket

【讨论】:

    【解决方案2】:

    你不能检查是否有扩展名吗? 顺便说一句,您不需要检查集合中的路径是否存在,因为集合将始终保留唯一的项目。

    list_objects 不返回任何指示项是文件夹还是文件。所以,这看起来很实用。

    请查看:https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.list_objects

    subfolders = set()
    current_path = None
    
    result = await self.s3_client.list_objects(Bucket=bucket, Prefix=prefix)
    objects = result.get("Contents")
    
    try:
        for obj in objects:
            current_path = os.path.dirname(obj["Key"])
            if "." in current_path:
                subfolders.add(current_path)
    except Exception as exc:
        print(f"Getting objects with prefix: {prefix} failed")
        raise exc
    

    【讨论】:

    • 我会试试的。我知道我不必检查我有检查的集合以在屏幕上打印任何新值,确实不需要
    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 2017-09-29
    • 2021-05-22
    • 1970-01-01
    • 2018-05-21
    • 2019-09-07
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多