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

新手上路,请多包涵

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

当前代码

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

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

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

也许它也将“文件”算作一个键?

原文由 ThatComputerGuy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 761
2 个回答

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

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

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

有关示例,请参阅: 确定文件夹或文件键 - Boto

原文由 John Rotenstein 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 vagabond 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题