簡體   English   中英

使用 Boto3 獲取特定 S3 文件夾中的對象數

[英]Get count of objects in a specific S3 folder using Boto3

試圖獲取 S3 文件夾中的對象數

當前代碼

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

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

這給我的計數是 1+S3 中的實際對象數。

也許它也將“文件”算作一個鍵?

假設您想計算存儲桶中的鍵數並且不想使用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)

“文件夾”實際上並不存在於 Amazon S3 中。 相反,所有對象都將其完整路徑作為其文件名 ('Key')。 我想你已經知道了。

但是,可以通過創建與文件夾同名的零長度對象來“創建”文件夾。 這會導致文件夾出現在列表中,如果通過管理控制台創建文件夾,就會發生這種情況。

因此,您可以從計數中排除零長度對象。

例如,請參閱:確定文件夾或文件鍵 - Boto

以下代碼完美運行

def getNumberOfObjectsInBucket(bucketName,prefix):
    count = 0
    response = boto3.client('s3').list_objects_v2(Bucket=bucketName,Prefix=prefix)
    for object in response['Contents']:
        if object['Size'] != 0:
            #print(object['Key'])
            count+=1
    return count

object['Size'] == 0將帶您到文件夾名稱,如果要檢查它們, object['Size'] != 0將帶您到所有非文件夾鍵。 示例 function 請撥打以下電話:

getNumberOfObjectsInBucket('foo-test-bucket','foo-output/')

如果條目超過 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'))

如果您有訪問該存儲桶的憑據,則可以使用這個簡單的代碼。 下面的代碼會給你一個列表。 列表理解用於提高可讀性。

過濾器用於過濾對象,因為在存儲桶中識別文件,使用文件夾名稱。 正如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()]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM