使用Boto3获取特定S3文件夹中的对象数

时间:2019-02-12 18:25:56

标签: python amazon-s3 boto3

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

当前代码

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

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

这使我成为S3中对象的实际数量+1。

也许它也将“文件”作为密钥吗?

2 个答案:

答案 0 :(得分:4)

假设您要计算存储桶中的键,并且不想使用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)

答案 1 :(得分:0)

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

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

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

有关示例,请参见:Determine if folder or file key - Boto