【问题标题】:Get count of objects in a specific S3 folder using Boto3使用 Boto3 获取特定 S3 文件夹中的对象数
【发布时间】:2019-02-12 18:25:55
【问题描述】:

试图获取 S3 文件夹中的对象数

当前代码

bucket='some-bucket'
File='someLocation/File/'

objs = boto3.client('s3').list_objects_v2(Bucket=bucket,Prefix=File)
fileCount = objs['KeyCount']

这给我的计数是 1+S3 中的实际对象数。

也许它也将“文件”计为键?

【问题讨论】:

  • 注意:objs['KeyCount'] 最大为 1000

标签: python amazon-s3 boto3


【解决方案1】:

假设您想计算存储桶中的键并且不想使用list_objects_v2 达到 1000 的限制。下面的代码对我有用,但我想知道是否有更好更快的方法来做到这一点!尝试查看boto3 s3连接器中是否有打包功能,但没有!

# connect to s3 - assuming your creds are all set up and you have boto3 installed
s3 = boto3.resource('s3')

# identify the bucket - you can use prefix if you know what your bucket name starts with
for bucket in s3.buckets.all():
    print(bucket.name)

# get the bucket
bucket = s3.Bucket('my-s3-bucket')

# use loop and count increment
count_obj = 0
for i in bucket.objects.all():
    count_obj = count_obj + 1
print(count_obj)

【讨论】:

  • 一种更好、更高效的计算迭代的方法是使用sum():count_obj = sum(1 for _ in bucket.objects.all())
【解决方案2】:

“文件夹”实际上并不存在于 Amazon S3 中。相反,所有对象都将其完整路径作为其文件名('Key')。我想你已经知道了。

但是,可以通过创建与文件夹同名的零长度对象来“创建”文件夹。这会导致文件夹出现在列表中,如果文件夹是通过管理控制台创建的,就会发生这种情况。

因此,您可以从计数中排除零长度对象。

例如,请参阅:Determine if folder or file key - Boto

【讨论】:

  • 是的,消除大小为 0 的对象并计算其余的对象有效!谢谢
【解决方案3】:

如果条目超过 1000 条,则需要使用分页器,如下所示:

count = 0
client = boto3.client('s3')
paginator = client.get_paginator('list_objects')
for result in paginator.paginate(Bucket='your-bucket', Prefix='your-folder/', Delimiter='/'):
    count += len(result.get('CommonPrefixes'))

【讨论】:

    【解决方案4】:

    如果您有访问该存储桶的凭据,那么您可以使用这个简单的代码。下面的代码会给你一个列表。列表理解用于提高可读性。

    过滤器用于过滤对象,因为在桶中识别文件,使用文件夹名称。正如 John Rotenstein 所言简明扼要。

    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()]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 2017-01-09
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多