Last active
February 15, 2019 06:25
-
-
Save viet-wego/fdb44e5d824e36062358804d2db17378 to your computer and use it in GitHub Desktop.
List all folder and size within a s3 bucket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import sys | |
import decimal | |
def main(): | |
bucket = sys.argv[1] | |
client = boto3.client('s3') | |
result = client.list_objects_v2(Bucket=bucket, Delimiter='/') | |
for o in result.get('CommonPrefixes'): | |
sub_prefix = o.get('Prefix') | |
objects = client.list_objects_v2(Bucket=bucket, Prefix=sub_prefix) | |
totalSize = sum(obj['Size'] for obj in objects['Contents']) | |
print( | |
sub_prefix[:-1] + ': {:.3f} MB'.format(decimal.Decimal( | |
totalSize)/decimal.Decimal(1024)/decimal.Decimal(1024))) | |
if __name__ == "__main__": | |
try: | |
main() | |
except Exception as error: | |
print('Error occurred. Please make sure that: \n - You have sys, decimal & boto3 lib installed. \n - You pass your bucket name in the parameter list. E.g. python3 s3-get-folder-size.py my-bucket\n') | |
print('***Error detail:') | |
raise error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment